PHP图片上传问题:在上传多个带图片的帖子时替换先前的图片

huangapple go评论55阅读模式
英文:

PHP Image Upload Issue: Replacing Previous Image When Uploading Multiple Posts with Images

问题

我面临的问题是关于我的PHP应用程序的图像上传功能。情景如下:

我有一个表单,用户可以创建一个帖子并上传与帖子相关联的图像。
当我上传带有图像的第一个帖子时,一切正常,图像正确保存在服务器文件夹Uploads中,名称为(例如,post1_image.jpg)。
然而,问题出现在我尝试上传具有与第一张图像相同名称的不同图像的第二个帖子时(例如,post1_image.jpg)。它不是将其保存为新图像,而是替换了与第一个帖子相关联的先前图像。
我如何修改我的PHP代码以确保每个上传的图像都获得唯一名称,并不覆盖任何现有图像?这是我当前用于处理图像上传的PHP代码的简化版本:

<?php
    include "config.php"; // 与服务器的连接

    // 文件上传
    if (isset($_FILES['fileToUpload'])) {
        $Errors = array();

        $File_Name = $_FILES['fileToUpload']['name'];
        $File_Size= $_FILES['fileToUpload']['size'];
        $File_Tmp = $_FILES['fileToUpload']['tmp_name'];
        $File_Type = $_FILES['fileToUpload']['type'];
        $File_ext = end(explode('.',$File_Name));
        $Extensions = array('jpeg','jpg','png');
        if (in_array($File_ext,$Extensions) === false) {
            $Errors[] = "此文件不允许上传。您只能上传jpeg,jpg和png文件";
        }
        if ($File_Size > 2097152) {
            $Errors[] = "您不能上传大于2MB的文件";
        }

        if (empty($Errors) == true) {
            // 生成唯一的文件名
            $Unique_File_Name = uniqid() . '_' . $File_Name;
            move_uploaded_file($File_Tmp, "upload/" . $Unique_File_Name);
        } else {
            print_r($Errors);
            die();
        }
    }

    session_start();
    $Title = mysqli_real_escape_string($conn, $_POST["post_title"]);
    $Description = mysqli_real_escape_string($conn, $_POST["postdesc"]);
    $Category = mysqli_real_escape_string($conn, $_POST["category"]);
    $date = date("D M,Y");
    $Auther = $_SESSION['name'];

    $sql = "insert into post (title,description,category,post_date,author,post_img) values ('{$Title}', '{$Description}', {$Category}, '{$date}', '{$Auther}','{$Unique_File_Name}');";
    $sql .= "Update category set post = post+1 where category_id = $Category;";

    if (mysqli_multi_query($conn, $sql)) {
        mysqli_close($conn);
        header('Location: http://'.$hostname.'/cms/admin/post.php');
    } else {
        echo "查询失败";
    }
    
?>

如果对如何解决此问题有任何见解或建议,将不胜感激!谢谢!

英文:

I'm facing an issue with my PHP application's image upload functionality. The scenario is as follows:

I have a form where users can create a post and upload an image associated with the post.
When I upload the first post with an image, everything works fine, and the image is correctly saved to the server Folder name Uploads with a name (e.g., post1_image.jpg).
However, the problem arises when I try to upload a second post with a different image but having the same name as the first image (e.g., post1_image.jpg). Instead of saving it as a new image, it replaces the previous image associated with the first post.
How can I modify my PHP code to ensure that each uploaded image gets a unique name and doesn't overwrite any existing images? Here's a simplified version of my current PHP code for handling the image upload:

<?php 
include "config.php"; // Connection with server
// File Upload
if (isset($_FILES['fileToUpload'])) {
$Errors = array();
$File_Name = $_FILES['fileToUpload']['name'];
$File_Size= $_FILES['fileToUpload']['size'];
$File_Tmp = $_FILES['fileToUpload']['tmp_name'];
$File_Type = $_FILES['fileToUpload']['type'];
$File_ext = end(explode('.',$File_Name));
$Extensions = array('jpeg','jpg','png');
if (in_array($File_ext,$Extensions) === false) {
$Errors[] = "This file is not allowed to upload. You can only upload jpeg , jpg and png";
}
if ($File_Size > 2097152) {
$Errors[] = "you cant upload file of size greater then 2MB";
}
if (empty($Errors) == true) {
move_uploaded_file($File_Tmp,"upload/". $File_Name);
}else{
print_r($Errors);
die();
}
}
session_start();
$Title = mysqli_real_escape_string($conn,$_POST["post_title"]);
$Description = mysqli_real_escape_string($conn,$_POST["postdesc"]);
$Category = mysqli_real_escape_string($conn,$_POST["category"]);
$date = date("D M,Y");
$Auther = $_SESSION['name'];
$sql = "insert into post (title,description,category,post_date,author,post_img) values ('{$Title}', '{$Description}', {$Category}, '{$date}', '{$Auther}','{$File_Name}');";
$sql .= "Update category set post = post+1 where category_id = $Category;";
// $result =  mysqli_multi_query($conn, $sql) or die ("Query unsucceful"); 
if (mysqli_multi_query($conn, $sql)) {
mysqli_close($conn);
header('Location: http://'.$hostname.'/cms/admin/post.php');
}else {
echo "Query Failed";
}
?>

Any insights or suggestions on how to resolve this issue would be greatly appreciated! Thank you!

答案1

得分: 1

你可以使用uniqid()函数来确保每个上传的图像都有一个唯一的名称。

move_uploaded_file($File_Tmp,"upload/".uniqid().$File_Name);

英文:

You can use the uniqid() function to ensure that each uploaded image gets a unique name.

> move_uploaded_file($File_Tmp,"upload/".uniqid().$File_Name);

huangapple
  • 本文由 发表于 2023年7月23日 16:46:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定