php html文件上传表单验证错误

时间:2014-03-03 18:52:00

标签: php html forms file upload

我遇到表单验证问题。当我没有选择要上传的文件时,我仍然会收到错误,只有png图像有效。我认为如果没有选择文件,$ _FILES数组将为空。

我做错了什么?

我的html表格摘录文件上传如下:

<label for="file">Filename
<span class="small">Upload image</span>
</label>
<input type="file" name="file" id="file">

我的php处理看起来像这样:

 $submitted_file = $_FILES['file'];

 if(isset($submitted_file)) {

    // verify the file PNG only
    $fileType = exif_imagetype($submitted_file["tmp_name"]);
    $allowed = array(IMAGETYPE_PNG);
    $max_filesize = 512000;

    if (!in_array($fileType, $allowed)) {
    $proceed = false;
    $arrErrors['submitted_file_ext'] = 'Please upload .png images only.';
    }
}

2 个答案:

答案 0 :(得分:0)

如果为空,则要检查的数组的字段[“tmp_name”]为null。请尝试使用此代码:

if(!empty($submitted_file["tmp_name"])) {

答案 1 :(得分:0)

正确的方法是检查$_FILES['error']

if ($_FILES['name']['error'] === UPLOAD_ERR_OK) {
    // file successfully uploaded
}

此处有更多信息http://ru2.php.net/manual/en/features.file-upload.php