duanji1482 2017-08-30 10:20
浏览 16
已采纳

如何处理文件上传名称

I'm trying to handle file uploads and now I face a dilemma. I have two options that I actually think about using when handling file name:

Option 1:

move_uploaded_file($_FILES['pdf']['tmp_name'], sprintf('./uploads/%s.%s', sha1_file($_FILES['pdf']['tmp_name']),$ext

Option 2:

move_uploaded_file($_FILES['pdf']['tmp_name'], sprintf('./uploads/%s.%s', "name_$date", $ext

First will generate hash with sha1_file which doesn't look pretty (and I would like to get that uploaded file name from DB and show it on page) but prevents multiple same file uploads.

Second gets a nice looking file name but doesn't prevent duplicates (file_exists seems to recognize duplicate but I couldn't stop move_upload_file)

What would you suggest me to do to get nice file name without file upload duplicates?

  • 写回答

2条回答 默认 最新

  • dtzk85937 2017-08-30 10:23
    关注

    Maybe a simple solution: You can create a temporary directory with the name of the sha1 hash and put in the filenames with their original name.

    This way, multi file uploads will go to different directories if they are different, but you will keep the original file name.

    Example:

    $uploadDir = "/your upload dir";
    $contentHash = sha1_file($_FILES['pdf']['tmp_name']);
    $tmpDir = $uploadDir . DIRECTORY_SEPARATOR . $contentHash;
    mkdir($tmpDir, 0777); 
    // add filename validation before storing it! 
    $fileName = $tmpDir . DIRECTORY_SEPARATOR . $_FILES['pdf']['name'];
    move_uploaded_file($_FILES['pdf']['tmp_name'], $fileName); 
    

    You will wind up with a directory structure like this:

    • 01BADCOFFEE123
      • test.pdf
    • (some other hash)
      • test.pdf
    • ...

    to later iterate the files, just use a recursive directory iterator:

    $uploadDir = "/your upload dir";
    $fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($uploadDir), \RecursiveIteratorIterator::LEAVES_ONLY);
    

    No need to store anything in the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?