PHP文件上传无法从Temp移动文件

时间:2018-10-19 19:45:06

标签: php html image-uploading

当我尝试在move_uploaded_file()脚本中使用upload.php时,它只返回编程的错误“某个地方发生了错误。请重试或联系管理员。”,无法将其移动到文件中似乎。我似乎无法找到问题所在,我确保表单具有所有必不可少的部分,例如enctype="multipart/form-data"等,并且一切正常,直到尝试将文件从tmp目录移动到上载目录。有见识吗?

console.php

<form action="upload.php" method="POST" enctype="multipart/form-data" data-ajax="false">
  <ul data-role="listview" class="ui-grid-a">
    <li><label for="admin">Posting As:</label><input type="text" placeholder="<?php echo $_SESSION['user']; ?>" name="admin" disabled></li>
    <li><label for="title">Post Title:</label><input type="text" name="title"></li>
    <li><label for="body">Post Body:</label><textarea name="body" placeholder="Type your post here. Feel free to use HTML!"></textarea></li>
    <li><label for="myfile">Upload Post Image:</label><input type="file" accept="image/*" id="myfile" name="myfile"></li>
    <li><input type="submit" id="submitPost" name="submitPost" value="SUBMIT"></li>
  </ul>
</form>

upload.php

<?php
    $currentDir = getcwd();
    $uploadDirectory = "./uploads/";

    $errors = []; // Store all foreseen and unforseen errors here

    $fileExtensions = ['jpeg','jpg','png','gif','svg']; // Get all the file extensions

    $fileName = $_FILES['myfile']['name'];
    $fileSize = $_FILES['myfile']['size'];
    $fileTmpName  = $_FILES['myfile']['tmp_name'];
    $fileType = $_FILES['myfile']['type'];
    $fileExtension = strtolower(end(explode('.',$fileName)));

    $uploadPath = $currentDir . $uploadDirectory . basename($fileName); 

    if (isset($_POST['submitPost'])) {

        if (! in_array($fileExtension,$fileExtensions)) {
            $errors[] = "This file extension is not allowed. Please upload a JPEG, JPG, GIF or PNG file";
        }

        if ($fileSize > 2000000) {
            $errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
        }

        if (empty($errors)) {

            $didUpload = move_uploaded_file($fileTmpName, $uploadPath);

            if ($didUpload) {
                echo "The file " . basename($fileName) . " has been uploaded";
            } else {
                echo "An error occurred somewhere. Try again or contact the admin";
            }
        } else {
            foreach ($errors as $error) {
                echo "These are the errors" . "\n" . $error;
            }
        }
    }
?>

2 个答案:

答案 0 :(得分:1)

首先检查目标路径是否存在,然后检查目标路径或文件夹是否具有读写权限。

答案 1 :(得分:1)

这可能是权限问题。您可以检查目录是否存在并且可写。

if (empty($errors)) {

  if(!is_dir($uploadPath)){
    mkdir($uploadPath, 0655);
  }

  if(!is_writable($upload_path)){
    chmod($upload_path, 0655); // Note 0655 is not a string but an int
  }

  // ... Rest of code ...