重命名上传的图像后,从数据库中提取时会显示损坏的图像

svujldwt  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(286)

如果我上传一个同名的图片,我的代码可以在我的位置重新命名它,但是当它从数据库中取出时,重复的图片会被破坏。我重命名和存储图像的代码是:
插入\u image.php

$image      = $_FILES['image'];
$name       = $_FILES['image']['name'];
$temp_name  = $_FILES['image']['tmp_name'];
$newname = $name; 
//print_r($_FILES); 
$location = realpath(dirname(__FILE__)).'/images/'.basename($name); 
$image_path = realpath(dirname(__FILE__)).'/images/';   
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);

if(file_exists($location)){
     $increment = 0;
     list($name, $extention) = explode('.', $location);
     while(file_exists($location)) {
         $increment++;
         $location = $name. $increment . '.' . $extention;
         //print_r($location);
         $newname = $name. $increment . '.' . $extention;
     }
 } 

 mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");

if(isset($newname)){
    if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
        //echo 'File uploaded successfully';
    }
    else{
        //echo "Failed to move...";
    }
}

任何更好的建议都会很有帮助。

wvt8vs2t

wvt8vs2t1#

location 变量(在while循环中)只存储文件名。您还需要完整路径。更改代码如下

$image      = $_FILES['image'];
$name       = $_FILES['image']['name'];
$temp_name  = $_FILES['image']['tmp_name'];
$newname = $name; 
//print_r($_FILES); 
$location = realpath(dirname(__FILE__)).'/images/'.basename($name); 
$image_path = realpath(dirname(__FILE__)).'/images/';   
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);

if(file_exists($location)){
     $increment = 0;
     list($name, $extention) = explode('.', $name);
     while(file_exists($location)) {
         $increment++;
         $location = realpath(dirname(__FILE__)).'/images/'.$name. $increment . '.' . $extention;
         $newname = $name. $increment . '.' . $extention;
     }
 } 

 mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");

if(isset($newname)){
    if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
        //echo 'File uploaded successfully';
    }
    else{
        //echo "Failed to move...";
    }
}

相关问题