运行 PHP 来自 HTML 的脚本导致空白 PHP 页

Running PHP Script from HTML Leads to Blank PHP Page

(注意:更新标题以更好地匹配问题)

我正在努力为 ajax 聊天添加图片上传功能,我已经编写了 HTML 和 PHP(基本上是 copied from W3Schools)来执行此操作.我在服务器上设置了一个测试 HTML 页面来测试图像上传并且工作正常 - 当按下 "Upload Image" 按钮(执行 PHP上传代码)。但是,一旦上传完成,页面就会切换到空白页面,其中包含我的 upload.php 文件的 URL。

我目前在 HTML 中使用模式来最初隐藏图片上传表单,并且仅在按下聊天中的 "Image" 按钮时才会出现。代码非常简单,正如我所说的,与上面 link 中看到的基本相同,但放在模态中。

在任何人抱怨之前,我知道 PHP 很容易被利用并且放在网站上时可能很危险,但在我的案例中这已被确定为 non-issue。

下面是图片上传模式的代码。请原谅所有 in-line CSS,我最终会将其移动到自己的样式表中,但一直使用 in-line 用于开发目的。请注意,显示设置为阻止调试。对于实时站点,它将设置为 none 并且使用 javascript 函数将其设置为在聊天模块中按下 "Image" 按钮时阻止。

<html>
    <body>
        <div id="imageUploadModal" style="display:block; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%;.
             overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
            <div style="background-color:#fefefe; margin:15% auto; padding:20px; border:1px solid #888; width:80%;">
                <span style="color:#aaa; float:right; font-size:28px; font-weight:bold;">&times;</span>
                <form action="upload.php" method="post" enctype="multipart/form-data">
                    Select image:
                    <input type="file" name="fileToUpload" id="fileToUpload"/>
                    <input type="submit" value="Upload Image" name="submit"/>
                </form>
            </div>
        </div>
    </body>
</html>

更新: 以下是upload.php的内容:

<?php
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is an actual image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        //The file is an image
        $uploadOk = 1;
    } else {
        //The file is not an image
        $uploadOk = 0;
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    //The file already exists
    $uploadOk = 0;
}

// Check file size
if (2000000 < $_FILES["fileToUpload"]["size"]) {
    //The file is too large
    $uploadOk = 0;
}

// Allow certain file formats
if (($imageFileType != "jpg") && ($imageFileType != "png")
    && ($imageFileType != "jpeg") && ($imageFileType != "gif")) {
    //Only JPG, JPEG, PNG, and GIF files are allowed
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    //The file was not uploaded
    exit();
// if everything is ok, try to upload the file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        exit();
    } else {
        //There was an error uploading the file
        exit();
    }
}
?>

编辑:已更新 HTML/Javascript

// Ajax image upload
$(document).ready(function() {
    $("#uploadForm").submit(function(event) {
        event.preventDefault();

        var $form = $("#uploadForm");
        var serializedData = $form.serialize();

        var request = $.ajax({
            type: "POST",
            url: "/upload.php",
            data: serializedData
        });

        request.done(function() {
            console.log("AJAX Success!");
            closeImageUploadModal();
        });
    })
});

HTML:

<div id="imageUploadModal" style="display:none; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%; 
    overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
    <div style="background-color:#0e0e0e; color:#aaa;  margin:15% auto; padding:20px; border:1px solid #888; width:50%;">
        <span id="close" style="color:#aaa; float:right; font-size:28px; font-weight:bold;" onclick="closeImageUploadModal()">&times;</span>
        <form id="uploadForm">
            <h3><b>Select image:</b></h3>
            <input type="file" name="fileToUpload" id="fileToUpload" accept=".jpg, .JPG, .png, .PNG, .jpeg, .JPEG, .gif, .GIF"/>
            <input type="submit" value="Upload Image" name="submit"/>
        </form>
    </div>
</div>

如何在不刷新或重定向的情况下上传文件。

方法一:插件

插件可能是最适合您的,因为它们通常经过良好测试并且相对没有错误并且几乎不需要任何工作即可获得它 运行。您可以使用许多插件,我在下面列出了它们。

jQuery File Uploader

Multiple File Upload Plugin

Mini Multiple File Upload

jQuery File Upload


方法 2:其他 Whosebug 答案

这类问题已经有很多答案了。我在下面列出了一些。

How can I upload files asynchronously?

jQuery AJAX file upload PHP

How to use $.ajax() for input field text AND FILE upload?

jQuery Ajax File Upload

File Upload Ajax PHP


要查看的其他来源

https://www.sanwebe.com/2012/06/ajax-file-upload-with-php-and-jquery

https://www.formget.com/ajax-image-upload-php/

如果您需要更多资源来查看,请尝试搜索:

How to upload file with AJAX and PHP

Uploading File with AJAX and PHP

Sending File to AJAX and PHP upload

File Upload AJAX and PHP


解决方案

HTML

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" onclick="UploadFile()" />
</form>

<progress></progress>

JavaScript 和 AJAX

Note: You will need jQuery for this section. Please link the lastest CDN to your document.

function UploadFile()
{
    $.ajax({
        url: 'upload.php',
        type: 'POST',

        data: new FormData($('form')[0]),

        cache: false,
        contentType: false,
        processData: false,

        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();

            if (myXhr.upload)
            {
                myXhr.upload.addEventListener('progress', function(e)
                {
                    if (e.lengthComputable)
                    {
                        $('progress').attr({
                            value: e.loaded,
                            max: e.total,
                        });
                    }
                }, false);
            }

            return myXhr;
        },

        success: function() {
                     // close modal here
                 }
    });
}

这确实有效,因为我已经测试过了。您需要稍微更改一下 PHP。

只需将您的 PHP 代码和 HTML 合并到一个文件中,然后在表单中自行提交。


    <?php
    $Fname = $_POST["Fname"];
    $Lname = $_POST["Lname"];
    ?>
    <html>
    <head>
    <title>Personal INFO</title>
    </head>
    <body>
    <form method="post" action="<?php echo $PHP_SELF;?>">
    First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
    Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
    </form>
    <?
    echo "Hello, ".$Fname." ".$Lname.".<br />";
    ?>