非常奇怪的PHP文件上传错误

时间:2015-11-16 04:01:29

标签: php html forms

我有一个表单,允许用户上传文件以及其他一些数据。然后将其传递给PHP文件,该文件尝试上载文件,然后将一些传递的数据以及文件位置写入JSON索引。但是,我尝试上传的图像中有一半以上只会打印

  

“抱歉,上传文件时出错。”

这是我的全部错误。奇怪的是,有些图像会同时显示每个错误代码,包括PHP错误

  

“Undefined index:img_upload”。

使用echo语句进行的一些检查表明,在这些情况下,图像数据似乎甚至没有传递给PHP函数。但是,当发生这些错误时,上传最终会成功。

PHP:

<?php

#Image code
$target_dir = "../BlogPosts/post_images/";
$target_file = $target_dir . basename($_FILES["img_upload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["img_upload"]["tmp_name"]);
    if ($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// // Check file size
//if ($_FILES["img_upload"]["size"] > 500000) {
//    echo "Sorry, your file is too large.";
//    $uploadOk = 0;
//}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
    echo "Sorry, only JPG, JPEG, PNG & 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["img_upload"]["tmp_name"], $target_file)) {
        echo "The file " . basename($_FILES["img_upload"]["name"]) . " has been uploaded.";


#All other code
        $postbody = $_POST["newpost_body"];
        $posttitle = $_POST["newpost_title"];
#Preparing the post summary
        $postsummary = substr($postbody, 0, 175);
        $postsummary = $postsummary . "...";
        $postsummary = strip_tags($postsummary);
        $postsummary = preg_replace("/&quot;/", "\"", $postsummary);
        $postsummary = preg_replace("/&#39;/", "'", $postsummary);


#Uploading post text
        $filepath = dirname(__FILE__) . "/../BlogPosts/";
        $fileid = time();
        $filename = $filepath . $fileid . ".html";
        $var_str = var_export($postbody, true);
        $var = "$postbody";
        file_put_contents($filename, $var);
        $posts = json_decode(file_get_contents(dirname(__FILE__) . "/../BlogPosts/posts.json"), true);
#$posts->append($fileid);
        $filedata = [
            "ID" => $fileid,
            "Title" => $posttitle,
            "Date" => gmdate("m.d.y", $fileid),
            "Summary" => $postsummary,
            "Thumb" => $target_file,
        ];

        array_push($posts['posts'], $filedata);

        $arr1 = $posts;
        file_put_contents(dirname(__FILE__) . "/../BlogPosts/posts.json", json_encode($arr1));
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}


        header('Location: #/blog');
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

HTML表单:

<form id="bpost_form" class="dropzone" method="post" action="/admin/writetofile.php" style="text-align:center" enctype="multipart/form-data">
            <input type="text" name="newpost_title"/>
            <br>
            <input type="file" name="img_upload" id="fileToUpload">
            <br>
            <textarea name="newpost_body" id="newpost" rows="10" cols="80">
                This is my textarea to be replaced with CKEditor.
            </textarea>
            <script>
                // Replace the <textarea id="editor1"> with a CKEditor
                // instance, using default configuration.
                CKEDITOR.replace('newpost');
            </script>
            <input type="submit"
                   value="Save"/>
        </form>

2 个答案:

答案 0 :(得分:3)

在这种情况下,我个人会将脚本分解为不同的任务,在本例中为两个。一个上传,第二个来处理你所指的#All other code。对于这个例子,我选择通过一个包含错误的类进行上传。它将根据上载成功返回truefalse,其他代码将根据该响应执行。它还将记录报告中的错误。这可能有用也可能没用。它基本上就是你所拥有的,只是重新组织:

<强> class.UploadFileEngine.php

class   UploadFileEngine
    {
        public  $errors;
        public  $fileName;

        private $target_dir;
        private $fileArray;
        private $fileTypes;
        private $target_file;

        public  function __construct($filetypes = array("jpg","jpeg","gif","png"))
            {
                // Assign accepted file types here
                $this->fileTypes    =   $filetypes;
                // Set the default input name from your form
                $this->setInput();
                // Set the errors array by default
                $this->errors       =   array();
            }

        public  function setDestination($target_dir = false, $make = true)
            {
                // Assign the destination
                $this->target_dir   =   $target_dir;
                // If the target has been left empty, don't do anything
                if(empty($this->target_dir))
                    return $this;
                // If the folder does not exist, try and make it
                if(!is_dir($this->target_dir) && $make)
                    mkdir($this->target_dir,0755,true);
                // Return this object for method-chaining purposes
                return $this;
            }

        public  function setInput($inputName = 'img_upload')
            {
                // Assign the input name (you can change this dynamically)
                $this->inputName    =   $inputName;
                $this->fileArray    =   (!empty($_FILES[$this->inputName]))? $_FILES[$this->inputName] : array();

                return $this;
            }

        public  function uploadFile()
            {
                // If there is no upload, just return false
                if(empty($this->fileArray))
                    return false;
                // Set up the file
                // This is all pretty much the same as yours...
                $this->fileName     =   basename($this->fileArray["name"]);
                $this->target_file  =   $this->target_dir.$this->fileName;
                $check              =   (!empty($this->fileArray["tmp_name"]))? getimagesize($this->fileArray["tmp_name"]) : false;
                $ext                =   pathinfo($this->target_file, PATHINFO_EXTENSION);

                if($check !== false) {
                        if(!file_exists($this->target_file)) {
                                if(in_array($ext, $this->fileTypes))
                                    return move_uploaded_file($this->fileArray["tmp_name"], $this->target_file);
                                else
                                    $this->errors[] =   'File extention invalid. Must be '.implode(", ",$this->fileTypes);
                            }
                        else
                            $this->errors[] =   'File already exists';
                    }
                else
                    $this->errors[] =   "File is not an image";

                return false;
            }

        public function getTargetFile()
            {
                return (!empty($this->target_file))? $this->target_file : false;
            }
    }

使用:

<?php
if(isset($_POST["submit"])) {
        include_once("class.UploadFileEngine.php");
        $destination    =   "../BlogPosts/post_images/";
        $uploader       =   new UploadFileEngine();
        $success        =   $uploader   ->setDestination($destination)
                                        ->uploadFile();

        $targetFile     = $uploader->getTargetFile();
        if($success) {
                // do rest of code here
            }
        else
            echo implode('<br />',$uploader->errors);
    }

答案 1 :(得分:0)

另请注意,如果您使用的是dropzone.js,则需要设置dropzone使用的文件名。在您的html表单中,您有<input type="file" name="img_upload" id="fileToUpload">,然后在您的PHP脚本中使用$_FILES["img_upload"]

但是,默认情况下,dropzone会将文件命名为“file”而不是“img_upload”。 您可以使用“paramName:”更改dropzone将使用的内容,请参阅http://www.dropzonejs.com/#configuration。或者只是将表单和php更改为“文件”。