【问题标题】:Uploading and overwriting a file that already exists上传和覆盖已经存在的文件
【发布时间】:2021-02-10 04:19:57
【问题描述】:

我已经创建了一个设置来上传一个文件,该文件根据产品 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']));
          }
        }

【问题讨论】:

    标签: php image upload overwrite vbulletin


    【解决方案1】:

    如果您上传与前文件同名的文件,前文件将被删除,新文件将被覆盖。 或者在上传新文件之前,您可以删除前文件并上传新文件。 您的某些代码是错误的,您应该编写真正的代码。据我了解,您必须更改代码:

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

    } ?>

    请注意 $ex_file。我不知道哪个变量有当前的旧文件。有些我改名了,方便大家看清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      相关资源
      最近更新 更多