继续使用我的PHP文件上传系统出现两个错误

时间:2014-10-22 05:22:11

标签: php html

我正在我的网站上设置文件上传服务。这是我到目前为止所得到的,

upload.php的

<form action="uploader.php" method="post" enctype="multipart/form-data"> 
 <input type="file" name="myFile">
 <br>
 <input type="submit" value="Upload">
</form>

uploader.php

<?php
define("UPLOAD_DIR", "/uploads");

if (!empty($_FILES["myFile"])) {
    $myFile = $_FILES["myFile"];

    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "<p>An error occurred.</p>";
        exit;
    }


    // ensure a safe filename
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    // verify the file is a GIF, JPEG, or PNG
    $fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
    $allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
    if (!in_array($fileType, $allowed)) {
        // file type is not permitted
        echo "<p>Unable to save file.</p>";
        exit;
    }



    // don't overwrite an existing file
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // preserve file from temporary directory
    $success = move_uploaded_file($myFile["tmp_name"],
        UPLOAD_DIR . $name);
    if (!$success) { 
        echo "<p>Unable to save file.</p>";
        exit;
    }

    // set proper permissions on the new file
    chmod(UPLOAD_DIR . $name, 0644);
}

我的目录中有一个名为uploads的文件夹,我希望我的文件上传到那里。

然而,当使用XAMMP运行它时,我尝试上传一个名为example.png的图像,它会出现以下错误。

Warning: move_uploaded_file(/uploadsexample.png): failed to open stream: Permission denied in C:\xampp\htdocs\assembly\uploader.php on line 37

Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpBAE5.tmp' to '/uploadsexample.png' in C:\xampp\htdocs\assembly\uploader.php on line 37
Unable to save file.

如果你能帮助我解决我的问题,我将非常感激!谢谢。

1 个答案:

答案 0 :(得分:3)

添加尾部斜杠/
define("UPLOAD_DIR", "/uploads");
                              ^ missing slash

将其更改为:

define("UPLOAD_DIR", "/uploads/");

注意你得到的错误=&gt; to '/uploadsexample.png'

并在

Warning: move_uploaded_file(/uploadsexample.png):
                                    ^

uploads之后,在uploads和文件名之间缺少斜杠。

另外,只是为了安全起见,如果仍然会抛出一个错误,它不允许您上传另一个“权限被拒绝”消息,请确保该文件夹确实可写,并且设置了适当的写入权限它

<强> N.B:

您可能需要将/uploads/修改为uploads/../uploads/,具体取决于脚本的执行位置。