Fix PHP image upload issue: replace previous image to upload new image in multiple posts
P粉788765679
P粉788765679 2023-09-14 11:27:48
0
1
352

I have an issue with the image upload functionality of my PHP application. details as following:

I have a form where the user can create a post and upload an image related to the post. When I upload my first post with an image, everything works fine and the image is saved correctly to the server in a folder calledUploadsand saved under a name (for example,post1_image. jpg). However, the problem arises when I try to upload a second post with a different image with the same name as the first image (for example,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 has a unique name and does not overwrite any existing images? Here is a simplified version of the PHP code I currently use to handle image uploads:

 2097152) { $Errors[] = "您不能上传大于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 "查询失败"; } ?>

Thank you very much for any insights or suggestions on how to solve this problem! Thanks!

P粉788765679
P粉788765679

reply all (1)
P粉936509635

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

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!