使用随机名称上传图像,并从目录中删除旧图像

I am trying to upload an image with a random name, also when I update the image, I want the previous image to be deleted.

Code below:

  $banner=$_FILES ['banner']['name'];
  $upload="../image/banner/";
  $target_file = $upload.basename($_FILES["banner"]["name"]);
  $imagefiletype= pathinfo($target_file,PATHINFO_EXTENSION);
  move_uploaded_file($_FILES["banner"]["tmp_name"], $target_file );

Any help will be appreciated.

When update your new images at that time first store old image name in variable. after update true then delete old image in your directory using "unlink" function.

$old_image = "xyz" // store old image name 

after update query success

unlink('../image/banner/'.$old_image); // delete old image in your directory 

You can do it like this.

$path = 'image/folder/'; $unique_name=time().uniqid(rand()); 
$File_with_location = $path . $unique_name . '.' . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION)); 
$filename = $_FILES["img"]["tmp_name"];        
move_uploaded_file($filename,  $File_with_location);

for deleting old image you can use this

$path = './root/home/folder/file.jpg';
if (unlink($path)) {
    echo 'success';
} else {
    echo 'fail';
}