php flie上传错误

时间:2015-12-29 08:54:30

标签: php html

我有错误。我用HTML 5和PHP进行了文件上传。当我尝试上传任何内容时,总会出现错误。这是代码:

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

upload.php的:

$target_path = "upload/";
$target_path = $target_path . basename($_FILES["fileToUpload"]["name"]);

if(isset($_POST["submit"])) {
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_path)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been                                    uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

2 个答案:

答案 0 :(得分:0)

如评论中所述,逻辑测试中使用的变量未在任何地方定义。我相信你有意这样的事情。

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

    $target_path = "upload/";
    $target_file = $target_path . basename( $_FILES["fileToUpload"]["name"] );

    if( isset($_POST["submit"]) ) {

        if ( file_exists( $target_file ) ) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
        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.";
        }
    }
?>

答案 1 :(得分:0)

只需更改 move_uploaded_file 调用的目标部分中的文件名

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