【问题标题】:!empty fails on image upload field check!empty 图像上传字段检查失败
【发布时间】:2015-11-16 14:56:05
【问题描述】:

我有一个包含大约 10 个字段的表单,最后一个是 imageUpload 字段,它不是必填字段。仅当填充了该字段时,我才尝试对文件进行 exif 检查。但是正如标题所述, !empty 在检查它是否已填充时失败,并且它只是继续,就像那里有一个文件一样,这当然会引发警告。 Warning: exif_imagetype(): Filename cannot be empty in

if(!empty($_FILES['imageUpload'])){
    $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
    $detectedType = exif_imagetype($_FILES['imageUpload']['tmp_name']);
    $isImage = !in_array($detectedType, $allowedTypes);
    if(!empty($isImage)){
        $errormsg[] = 'This is not a valid image file.';
    }
}

这是该字段的 var_dump。 array(1) { ["imageUpload"]=> array(5) { ["name"]=> string(0) "" ["type"]=> string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(4) ["size"]=> int(0) } }

那我做错了什么?

【问题讨论】:

  • $_FILES['imageUpload'] 不为空,它包含一堆空字符串 ["name"]=> string(0) "" ["type"]=> string(0) " " ["tmp_name"]=> string(0) "" ["error"]=> int(4) ["size"]=> int(0)
  • 如他所说。尝试在其中一个上检查为空。

标签: php forms file-upload


【解决方案1】:

试试下面的代码:

if (!empty($_FILES['imageUpload']['tmp_name'])){
    $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
    $detectedType = exif_imagetype($_FILES['imageUpload']['tmp_name']);
    $isImage = !in_array($detectedType, $allowedTypes);
    if(!empty($isImage)){
        $errormsg[] = 'This is not a valid image file.';
    }
}

【讨论】:

  • 好吧,这行得通,但请解释一下为什么它不能以其他方式工作,$_FILE 数组的值都是 0。
  • 这意味着 !empty 检查会看到 $_FILES['imageUpload'] 中的嵌套数组。结论:$_FILES['imageUpload'] 不为空。
【解决方案2】:

查看文件的tmp_name

if (!empty($_FILES['imageUpload']['tmp_name'])) {
    // do stuff
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多