【问题标题】:After renaming uploaded image, broken image is shown when fetched from database重命名上传的图像后,从数据库中获取时显示损坏的图像
【发布时间】:2023-03-12 16:52:01
【问题描述】:

如果我上传同名图片,我的代码可以在我的位置重命名它,但是当它从数据库中获取时,重复的图片会损坏。我重命名和存储图像的代码是:

insert_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...";
    }
}

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

【问题讨论】:

    标签: php mysql image mysqli file-upload


    【解决方案1】:

    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...";
        }
    }
    

    【讨论】:

    • 不起作用。检查了它。它将 $location 的值更改为如下所示: C:\xampp\htdocs\proj/images/C:\xampp\htdocs\proj/images/imagen.jpg
    • 能否请您重新检查并提出建议?
    • 你会检查更新的答案吗?我已更改此行:list($name, $extention) = explode('.', $name);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2015-06-09
    相关资源
    最近更新 更多