upload.php 在我的服务器上不工作

upload.php is not working on my server

以下脚本复制自 W3Schools http://www.w3schools.com/php/php_file_upload.asp

脚本没有将图像上传到 uploads/ 目录 - 我的脚本有问题吗?或者是否需要执行一些额外的操作才能使脚本正常工作?

目录名称: "uploads/"

文件名: "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;
    }
}
?>
<!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>


编辑


以下脚本现在会出现上述错误

<?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;
    }

    // Copy the file to target folder
    if ($uploadOk) {
        move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], target_dir .  $target_file );
    }
}
?>
<!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>

您的代码中没有任何函数可以将上传的文件复制到目标目录中。

你必须添加这个:

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir .  $target_file )

参加这个post中的问题作者评论,我更新了代码以创建文件夹,如果它不存在。

所以你的代码应该像这样:

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;
    }

    // Copy the file to target folder
    if ($uploadOk) {

       // Check if the upload directory exists and create if necessary
       if (!is_dir($target_dir)) {
           mkdir($target_dir);
       }

        move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir .  $target_file );
    }

}