php 无法上传文件

uploading of file does not work in php

我正在开发 php Web 应用程序,我使用以下代码从本地计算机将文件上传到服务器。

        <form action="upload.php" method="post" enctype="multipart/form-data">
         Select file to upload:
        <input type="file" name="fileToUpload" id="fileToUpload" value="c:/passwords.txt">
        <input type="submit" value="Upload" name="submit">
        </form>

upload.php

$target_dir = "uploads/";
        $target_file =  $target_dir .basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;



        if ($_FILES["fileToUpload"]["size"] > 5000000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }


        if ($uploadOk == 0) {
           echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
        } else {
        echo $_FILES['fileToUpload']['name']."<br>";    
        if(move_uploaded_file($_FILES["fileToUpload"]["name"], $target_file)) {       
             echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
          } else {
             echo "Sorry, there was an error uploading your file.";
           }
        }

但是上面的代码不起作用。我检查了上传文件夹权限

drwxrwxrwx 2 ankit ankit 4096 Aug  2 13:41 uploads

这似乎是可写的。我使用以下命令更改了我的项目权限

  sudo chmod -R 777 /var/www/myproject

但我仍然无法上传服务器上的文件。我可以知道我哪里错了吗?

更改此行:

$_FILES["fileToUpload"]["name"] // contains the original name of the uploaded file from the user's computer

$_FILES["fileToUpload"]["tmp_name"] // tmp_name will contain the temporary file name of the file on the server

move_uploaded_file 的文档。您要移动 uploaded 文件! ;-)

它会帮助你

move_uploaded_file 期望参数一是源,即 tmp_name

所以改变

if(move_uploaded_file($_FILES["fileToUpload"]["name"], $target_file)) {

if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

在您的评论中,您说当您使用

时会得到 error 1
print_r($_FILES);

这是由于

 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',

所以这样做

upload_max_filesize = 'Size'; // whatever you want

Documentation about $_FILES errors