php上传脚本不起作用

时间:2015-08-05 16:06:58

标签: php file upload

我想在我的主页上上传图片。 我使用w3schools的脚本来做到这一点:

这是upload.html

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

这是upload.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !="jpeg" && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

我已经创建了一个文件夹/ var / www / uploads / 当尝试上传3KB jpeg时,我得到了这个输出:

File is an image - image/jpeg.
Sorry, there was an error uploading your file.
Array ( [fileToUpload] => Array ( [name] => Test Bild Website Upload.jpg [type] => image/jpeg [tmp_name] => /tmp/phpyxW0TX [error] => 0 [size] => 2999 ) )

我是php的初学者,真的不知道问题是什么。 也许有人在那里可以帮助我。 :)

1 个答案:

答案 0 :(得分:3)

  1. 通过在命令行执行此操作,检查您是否可以上传文件:

    chmod -R 777 /var/www/uploads/

  2. 然后尝试上传内容。如果可行,您知道这是权限问题。但您不希望将上传文件夹保留为777权限(允许所有人访问)

  3. 如果是权限问题,请按以下方式执行权限:

    chown [your username]:www-data -R /var/www/uploads/

    chmod -R 775 /var/www/uploads/

  4. 这会将文件夹的组分配更改为www-data,这通常是在Ubuntu Linux服务器上运行的apache。