【问题标题】:php file image upload validationphp文件图片上传验证
【发布时间】:2017-03-26 15:23:07
【问题描述】:
   clearstatcache();
    if($_FILES['images']){
        if ($_FILES['images']['error'] !== UPLOAD_ERR_OK) {
               $error[] = "Upload failed with error code " . $_FILES['images']['error'];                                
       }

        $info = getimagesize($_FILES['images']['tmp_name']);
        if ($info === FALSE) {
           $error[] = "Unable to determine image type of uploaded file";
        }

        if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
                $error[] = "Not a gif/jpeg/png";
        }
        if ($_FILES["images"]["size"] > 100000) {//1mb limit
        $error[] = "Sorry, your file is too large.";
        }
}

这是我的 php 代码。检查文件是否为空。而且我要。如果文件存在,则 php 将检查文件图像。但是如果用户没有选择图像。验证将忽略它。我无法调试它。如果我没有选择图像代码仍然验证和错误说Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\savings\LiveUpdate.php on line 10

【问题讨论】:

标签: php


【解决方案1】:

您没有发布您的 html,但名称 images 表明您进行了多次上传。

您应该指定数组的元素。让我说[0]。查看更多文档:http://php.net/manual/en/features.file-upload.multiple.php

像这样更改你的代码(参见添加的else,因为如果你的上传失败,你只需要得到错误!)

clearstatcache();

if(is_array($_FILES['images'])){
    if ($_FILES['images']['error'][0] !== UPLOAD_ERR_OK) {
       $error[] = "Upload failed with error code " . $_FILES['images']['error'][0];                                
    }
    else {
        $info = getimagesize($_FILES['images']['tmp_name'][0]);
        if ($info === FALSE) {
            $error[] = "Unable to determine image type of uploaded file";
        }

        if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
            $error[] = "Not a gif/jpeg/png";
        }
        if ($_FILES["images"]["size"][0] > 100000) {//1mb limit
            $error[] = "Sorry, your file is too large.";
        }
    }
}

【讨论】:

  • 我担心自从他们在 Stack 上创建帐户以来,OP 一直在尝试上传文件。看看他们所有的问题stackoverflow.com/users/7148641/kenneth-suaverdez - 我想你可能会很长一段时间。
  • 它的工作。但我还有一个问题。如果我只是提交(我没有更改文件或打开任何文件)我的代码仍然检查即使我没有选择文件和 php 错误警告:getimagesize():C:\xampp\htdocs\savings\ 中的文件名不能为空第 10 行的 LiveUpdate.php
  • 您在评论时我正在编辑我的答案。查看我的编辑。
猜你喜欢
  • 2018-07-19
  • 2017-05-28
  • 2011-04-01
  • 1970-01-01
  • 2021-06-11
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多