dongtingrun4973 2017-07-08 18:24
浏览 75
已采纳

从HTML运行PHP脚本导致空白PHP页面

(Note: Updated title to better match the question)

I am working on adding an image upload feature to ajax chat, and I have the HTML and PHP already written (basically copied from W3Schools) to do this. I have a test HTML page set up on the server to test the image uploads and that works just fine - the form works and the file is uploaded when the "Upload Image" button is pressed (to execute the PHP upload code). However, once the upload is complete the page switches to a blank page with the URL for my upload.php file.

I am currently using a modal in HTML to initially hide the image upload form and only appear when the "Image" button in the chat is pressed. The code is very simple, and as I said is basically the same as seen in the above link but placed inside a modal.

And before anyone complains, I know PHP is easy to exploit and can be dangerous when put on a website but this has been determined to be a non-issue in my case.

Below is the code for the image upload modal. Please pardon all the in-line CSS, I will eventually move it to its own stylesheet but have been using in-line for development purposes. Note that display is set to block for debugging. For the live site it would be set to none and a javascript function is used to set it to block when the "Image" button is pressed in the chat module.

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

UPDATE: Below are the contents of 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();
    }
}
?>

EDIT: Updated 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>
  • 写回答

2条回答 默认 最新

  • duanbamo0127 2017-07-12 12:18
    关注

    How to upload a file without refreshing or redirecting.

    Method 1: Plugins

    Plugins would probably be the best for you, since they are usually well tested and relatively bug free and require hardly any work to get it running. There are a number of plugins you can use, I have them listed below.

    jQuery File Uploader

    Multiple File Upload Plugin

    Mini Multiple File Upload

    jQuery File Upload


    Method 2: Other StackOverflow Answers

    There has been plenty of answers for this type of problem. I have listed some below.

    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


    Additional Sources to look at

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

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

    If you need more sources to look at try searching:

    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


    Solution

    HTML

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

    JavaScript and 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
                     }
        });
    }
    

    This does work since I have tested it. You will need to change your PHP a little.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败