多个图像上传无法仅上传第一个图像 [英] multiple Image upload fails to upload only the first image

查看:88
本文介绍了多个图像上传无法仅上传第一个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,允许用户上传多张图片,每张图片的上限为2MB.提交表单后,图像将存储在服务器上(例如本例中的我的计算机).

I have a form that allows the user to upload multiple images, with each image capped at 2MB. After the form is submitted, the images would be stored on the server(E.g my computer in this case).

问题 上载多个文件时,上载的第一个图像将始终无法上载到服务器,而其他图像(例如第二,第三等)则可以成功保存到我的计算机中.仅使用一张图片,该图片也无法上传.

PROBLEM When uploading multiple files, the first image that is uploaded will always fail in uploading to the server, while the others(E.g 2nd,3rd, etc) are able to be saved to my computer successfully.When testing the form with just ONE image, the image also fails to upload.

我得出的结论是,尽管我看不到为什么会出现这种情况,但通过表单提交的第一张图像将始终无法上传,因为我能够成功地回显图像文件的tmp_name.

I've concluded that the first image that is submitted through the form will always fail to upload though i fail to see why that is the case as i am able to echo the tmp_name of the image files successfully.

我的代码(提取):

  if(isset($_FILES['upload']['tmp_name']))
 {
$numfile=count($_FILES['upload']['tmp_name']);

    for($i=0;$i<$numfile;$i++)
    {
        if(!empty($_FILES['upload']['tmp_name'][$i]))
        {
            if(is_uploaded_file($_FILES['upload']['tmp_name'][$i]))
            {

                //Conditionals for uploaded file
                $foldername=$_SESSION['UserId'];
                $cat=$_POST['category'];
                $sub=$_POST['subcat'];
                $itemname=$_POST['itemname'];
                $allowed_filetypes=array('.jpg','.gif','.bmp','.png','.JPG');
                $max_filesize = 2097152; // Maximum filesize in BYTES (currently 2.0MB).
                $upload_path = 'C:\Users\Kence\Desktop\UniServer\www\images\\'.$foldername.'\\'.$cat.'\\'.$sub.'\\'.$itemname.'\\'; // The place the files will be uploaded to.

                //Checks if Folder for User exists
                //If not, A folder for the user is created to store the user's images
                if(!is_dir($upload_path))
                {
                    $upload_path=mkdir($upload_path,0644,true);
                }

                $filename = $_FILES['upload']['name'][$i]; // Get the name of the file (including file extension).
                $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.

                // Check if the filetype is allowed, if not DIE and inform the user.
                if(in_array($ext,$allowed_filetypes))
                {
                    if(filesize($_FILES['upload']['tmp_name'][$i])<$max_filesize)
                    {
                        if(is_writable($upload_path))
                        {echo"$upload_path <br>";
                        print_r($_FILES);
                            if(!move_uploaded_file($_FILES['upload']['tmp_name'][$i],"$upload_path" . $filename))
                            {
                                $errormsg="Upload Failed.Error in moving file";
                            }
                        }
                        else
                        {
                        $errormsg="Image Upload Failed.";
                        }
                    }
                    else
                    {
                        $errormsg="Upload failed.ONly images below 2MB are allowed";
                    }
                }
                else
                {
                    $errormsg="Error. Only JPEG,PNG and BMP files are allowed";
                }

            }
            else
            {
                $errormsg="Error.File not uploaded";
            }
        }
    }

}
else
{
$errormsg="Upload failed";
}

错误消息 我收到错误消息

错误.文件未上传

Error.File not uploaded

表单代码:

<body onload="getcategory()">
  <form action="<?PHP echo $_SERVER['PHP_SELF'] ?>" name="additem" enctype="multipart/form-data" method="POST">
<table>
<tr>
  <td>Select Category: </td><td>
    <select name="category" id="category" onchange="getsubcategory(this)">
      <option disabled="disabled" value="">Choose a category</option>
    </select>
  </td>
</tr>
<tr>
  <td>Select SubCategory</td>
  <td>
    <select id="subcat" name="subcat">
      <option value=""></option>
    </select>
  </td>
</tr>
<tr>
  <td>Item Name</td>
  <td><input type="text" name="itemname" size="30" maxlength="50" required="required"></td>
</tr>
<tr>
  <td>Item Price</td>
  <td><input type="number" name="itemprice" size="30" min="1" required="required"></td>
</tr>
<tr>
  <td>Item Info</td>
  <td><textarea name="iteminfo" col="40" rows="10" maxlength="300" required="required"></textarea>
</tr>

<tr>
  <td>Filename:</td>
  <td><input type="file" name="upload[]" /></td>
</tr>

<tr>
  <td>Filename:</td>
  <td><input type="file" name="upload[]" /></td>
</tr>

<tr>
  <td>Filename:</td>
  <td><input type="file" name="upload[]" /></td>
</tr>

<tr>
  <td>Filename:</td>
  <td><input type="file" name="upload[]" /></td>
</tr>

<tr>
  <td>Filename:</td>
  <td><input type="file" name="upload[]" /></td>
</tr>
<tr>
 <td colspan="2"><input type="SUBMIT" name="Button" value="Submit"></td>
</tr>
<tr>
  <td colspan="2"><?PHP if(isset($errormsg)){echo"$errormsg";}?></td>
</tr>       
<tr>
  <td colspan="3"><font color="#FF0000"></font></td>            
</tr> 

即使我能够print_r ($_FILES)并且我尝试上传的所有图像的tmp_name也会成功显示.

Even though i am able to print_r ($_FILES) and the tmp_name of all the images im trying to upload will display successfully.

编辑 已采取/尝试过的步骤 添加了if(!empty)检查,以便仅处理带有tmp_name的上载,因此将忽略空上载,从而消除了错误(感谢Sven提供帮助)

EDIT Step Taken/Tried Added an if(!empty) check so that only uploads with tmp_name are processed.Empty uploads are thus ignored, thereby removing the error(Credits to Sven for his kind help)

Error.File not uploaded

但是,即使如此,提交给表单的第一张图片也将不保存(即,如果我仅上传一张图片,是否会失败,没有任何错误,以及是否上传了图片)多张图片,只有第一张图片不会被上传,而其余图片将被成功保存.)但是,如果我刷新页面(从而重新提交相同的表格),那么第一张图片将被保存.

However, even with that, the first image that is submitted to the form will NOT be saved(I.e if i upload just one image, if would fail,without any errors, and if i upload multiple images, only the first image would not be uploaded while the rest would be saved successfully.) However, if i were to refresh the page(thereby resubmitting the same form) the first image would then be saved.

这里的问题是文件路径不可可写,导致第一张图像无法保存.但是,令我困惑的是,如果第一张图像的文件路径不可写,为什么随后的图像在相同的代码上运行时为何它们具有有效的文件路径?另外,为什么刷新页面(然后重新提交表单)会神奇地使第一个图像成功保存(这表明文件路径现在可写了?)

The problem here is that the file path is NOT writable, causing the first image to not be saved.However what is confusing me is that, if the file path for the first image is not writable, why would the subsequent images have a valid file path, when they are running on the same code? Also, why would refreshing the page( and thus resubmitting the form) magically let the first image be saved successfully(which eans the file path is now writable?)

我的print_r($ _ FILES);

Array ( 
    [upload] => Array ( 
        [name] => Array ( 
            [0] => download (1).jpg 
            [1] => download.jpg 
            [2] => 
            [3] => 
            [4] => 
        ) 
        [type] => Array ( 
            [0] => image/jpeg 
            [1] => image/jpeg 
            [2] => 
            [3] => 
            [4] => 
        ) 
        [tmp_name] => Array ( 
            [0] => C:\Users\Kence\Desktop\UniServer\tmp\php474.tmp 
            [1] => C:\Users\Kence\Desktop\UniServer\tmp\php475.tmp 
            [2] => 
            [3] => 
            [4] => 
        ) 
        [error] => Array ( 
            [0] => 0 
            [1] => 0 
            [2] => 4 
            [3] => 4 
            [4] => 4 
        ) 
        [size] => Array ( 
            [0] => 6229 
            [1] => 6984 
            [2] => 0 
            [3] => 0 
            [4] => 0 
        ) 
    ) 
)

有人可以指出我在哪里做错什么吗?在过去的3个小时里,我一直在尝试,但我仍然不知道自己在做什么错,这让我发疯了!

Could someone point out where and what im doing wrong? I've been trying for the past 3 hours and i still don't know what i'm doing wrong and it's driving me crazy!

已解决

RESOLVED

找出我的错误.

我最初写过

if(!is_dir($upload_path))
{
    $upload_path=mkdir($upload_path,0644,true);
}

我将其更改为

if(!is_dir($upload_path))
{
    mkdir($upload_path,0644,true);
}

解决了我遇到的错误.我这真是愚蠢的错误

Which solved the errors i was getting. Really stupid mistake on my part

推荐答案

查看转储,并与您的代码进行比较.

Look at your dump, and compare with your code.

即使没有文件上传,您的代码也会访问所有上传字段,例如,在字段3、4和5中.因此,您的代码会遍历所有这些文件,并在空字符串上使用realpath().

Your code accesses ALL upload fields, even if there is no file uploaded, for example in fields 3, 4 and 5. So your code iterates over ALL these files and uses realpath() on an empty string.

这将触发错误消息错误.文件未上传".这是正确的,因为文件3、4和5没有上传,它们留空了.

This will trigger the error message "Error.File not uploaded". Which is correct because file number 3, 4 and 5 were not uploaded, they were left empty.

您的代码必须处理这个问题.

Your code has to deal with this.

作为安全功能,请不要使用realpath(),请使用is_uploaded_file(). PHP具有在上载期间创建的文件名列表,并且仅应允许这些文件在上载脚本中进行处理.即使攻击者诱骗PHP操纵"tmp_name",您也不想触摸任何其他文件.

And as a security feature, do not use realpath(), use is_uploaded_file(). PHP has a list of filenames that were created during the upload, and only those files should be allowed to process in the upload script. You do not want to touch any other files, even if an attacker tricked PHP into manipulating the "tmp_name".

这篇关于多个图像上传无法仅上传第一个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆