【问题标题】:What do I do wrong in my php upload script?我在我的 php 上传脚本中做错了什么?
【发布时间】:2020-02-04 05:43:28
【问题描述】:

所以,今天我尝试制作一个 PHP 上传脚本,但遇到了一个问题……它没有上传文件,我查看了问题所在,我发现 if(move_uploaded_file($_FILES['file']['tmp_name'], $target_file)){ 行有问题,需要你们的帮助

if(isset($_POST['but_upload'])){
       $maxsize = 5368706371; // 5GB

       $name = $_FILES['file']['name'];
       $target_dir = "videos/";
       $target_file = $target_dir . $_FILES["file"]["name"];
       $id = generateRandomString();

       // Select file type
       $videoFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

       // Valid file extensions
       $extensions_arr = array("mp4","avi","3gp","mov","mpeg");

        // Check extension
      if( in_array($videoFileType,$extensions_arr) ){

          // Check file size
          if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) {
            echo "File too large. The file must be less than 5GB.";
          }else{
            // Upload
            if(move_uploaded_file($_FILES['file']['tmp_name'], $target_file)){
              echo ("working!");
            }
          }

      }else{
          echo "Invalid file extension.";
      }

     }
     ?>
<!doctype html>
<head lang="en">
</head>
<body>
<form method="post" enctype='multipart/form-data'>
        <input type="file" name="file" id="file">
        <input type="submit" name="but_upload">
    </form>
</body>
</html>

generateRandomString 函数在另一个文件中

编辑: error.log 告诉我:

[06-Oct-2019 16:26:49 America/New_York] PHP Warning:  move_uploaded_file(videos/VSkzuJn0aZYoLvNLJwv3IrFNA9PV1zjfd4MfoXP3rjl1Nm7uW8--Peek 2019-05-20 18-11.mp4): failed to open stream: No such file or directory in /home/myacc/website.com/index.php on line 34

[06-Oct-2019 16:26:49 America/New_York] PHP Warning:  move_uploaded_file(): Unable to move '/tmp/phpTOsPRj' to 'videos/VSkzuJn0aZYoLvNLJwv3IrFNA9PV1zjfd4MfoXP3rjl1Nm7uW8--Peek 2019-05-20 18-11.mp4' in /home/myacc/website.com/index.php on line 34

【问题讨论】:

  • 您能否更具体地说明问题的细节?有错误吗?有什么事吗?如果文件太大,它会超时吗?是否启用错误报告?
  • 而不是videos 目录的相对路径,我建议使用完全限定路径,看看是否有帮助
  • @RamRaider 不,同样的错误会发生
  • 你能显示新路径吗?我看到你编辑了这个问题,但不确定我在上面看到的是什么(如果是最新的路径还是以前的)
  • @RamRaider 不是我,

标签: php html forms file-upload


【解决方案1】:

使用videos/ 作为路径表明上传文件夹位于当前工作目录中,而这可能的工作经验告诉我,使用完整路径总是被证明更可靠 - 所以也许这可能会有所帮助?

$target_dir = __DIR__ . "/videos/";

if( !file_exists( $target_dir ) ){
    mkdir( $target_dir, 0777, true );
    clearstatcache();
}

$target_file = $target_dir . $_FILES["file"]["name"];// ... etc as before

【讨论】:

  • 什么是 cleanstatcache()?
  • 哎呀——应该是 clearstatcache。 "PHP caches the information certain functions return in order to provide faster performance" - php.net/manual/en/function.clearstatcache.php
  • 你是个英雄,非常感谢,它有效,我知道为什么它没有
  • 没问题,很高兴它有帮助。也许考虑接受作为解决方案?!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 2011-11-03
  • 2010-10-23
  • 1970-01-01
  • 2019-11-13
相关资源
最近更新 更多