PHP和图像上传,在同一页面上显示服务器端错误



我有一个表单,它使用uploads.php。请参阅以下内容:

<?php
    include 'config/database.php';
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // 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" && $imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx") {
        echo "Sorry, only JPG, JPEG, PNG, DOC, PDF & 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.";
        }
    }
    header("Location: http://same-page-the-form-is-on.php");
 ?>

表单(index.php):

<form id="myForm" action="uploads.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" id="simple-post" value="Upload File Here" name="submit">
</form>

<?php
            $dir = "uploads/";
            $files = array_diff(scandir($dir), array('..', '.'));
            echo "<select>";
            foreach($files as $item ) {
                echo "<option value='.$item.'>" . $item . "</option>n";
            }
            echo "</select>";
        ?>

因此,根据上传时发生的情况,无论是已经存在的文件、文件太大还是文件扩展名错误,我希望服务器端错误消息显示在index.php上。对此,正确的方法是什么?异步传输

您可以从Index.php调用一个进行服务器端验证的函数,并将该函数抛出的错误返回到该Index.php并将其回显。如果设置了某个POST变量,则可以启动该函数。

最新更新