Uploading and overwriting a file that already exists

233 Views Asked by At

I Have created a setting to upload a file that names the file based on the product ID, with the help of a few submissions on here I have managed to get it functional. Some times the upload does not want to overwrite my file though. Are there any noticeable errors within my script?

$dir = DIR . '/images/productthumbs/';
        if (!is_dir($dir))
        {
            die(construct_phrase($vbphrase['invalid_directory'], $dir));
        }
        $ext = substr($file['name'], strrpos($file['name'], '.'));
        $new_file = $dir . basename('thumbnail_product_' . $id . $ext);
        print_dots_start($vbphrase['please_wait_while_upload']);
        if(file_exists($new_file)) unlink($new_file);{
          move_uploaded_file($new_file);
          if (!move_uploaded_file($file['tmp_name'], $new_file))
          {
            print_dots_stop();
            die(construct_phrase($vbphrase['error_upload'], $file['error']));
          }
        }
1

There are 1 best solutions below

0
Filayer On

If you upload file with same name of ex file, ex file will be removed and new file will be overwrited. Or before upload new file you can remove ex file and upload a new file. Some of your codes are wrong you should write true codes. As I understand you have to change code with :

<?php 
   $dir = DIR . '/images/productthumbs/';
   if (!is_dir($dir))
   {
      die(construct_phrase($vbphrase['invalid_directory'], $dir));
   }
   $ext = substr($file['name'], strrpos($file['name'], '.'));
   $new_file = $dir . basename('thumbnail_product_' . $id . $ext);
   print_dots_start($vbphrase['please_wait_while_upload']);
   $ex_file="same path of ex file"; // you have to remove ex file
   if(file_exists($ex_file))
  {
     unlink($ex_file); // with this code you remove ex file
  if (!move_uploaded_file($file['tmp_name'], $new_file))
  {
    print_dots_stop();
    die(construct_phrase($vbphrase['error_upload'], $file['error']));
  }

} ?>

Please be carefull about $ex_file. I dont know which variable has current old file. Some I renamed it for you to understand clearly.