首页 > 解决方案 > 上传和覆盖已经存在的文件

问题描述

我已经创建了一个设置来上传一个文件,该文件根据产品 ID 命名文件,在此处提交的一些内容的帮助下,我设法使其正常工作。有时上传并不想覆盖我的文件。我的脚本中是否有任何明显的错误?

$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']));
          }
        }

标签: phpimageuploadoverwritevbulletin

解决方案


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.


推荐阅读