php文件图片上传验证

时间:2016-11-12 15:07:34

标签: php

   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

1 个答案:

答案 0 :(得分: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.";
        }
    }
}