if语句验证文件上传,但错误仍然显示?

时间:2012-03-29 12:29:24

标签: php image forms validation file-upload

我有一个PHP验证语句,用于在HTML表单上上传文件。如果文件不是图像或不支持文件扩展名,则会打印错误。 if语句指出如果$_FILES为空以验证它,并显示相应的错误。问题是虽然文件上传不是必需的输入,但即使$_FILES变量为空,也会显示错误消息“文件似乎不是图像”?有人可以帮忙吗

error_reporting (E_ALL ^ E_NOTICE);

if($_FILES != "") // [START FILE UPLOADED]
{
    include 'image_validate.php';

    $file = $_FILES['eventPhoto'];

    $file_name = $file['name'];

    $error = ''; // Empty

    // Get File Extension (if any)
    $ext = strtolower(substr(strrchr($file_name, "."), 1));

    // Check for a correct extension. The image file hasn't an extension? Add one
    if($validation_type == 1)
    {
        $file_info = getimagesize($_FILES['eventPhoto']['tmp_name']);

        if(empty($file_info)) // No Image?
        {
            $error .= "<br/><div class='submitEventErrors'>The uploaded file doesn't seem to be an image.</div><br/>";
        }
        else // An Image?
        {
            $file_mime = $file_info['mime'];

            if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
            {
                $extension = $ext;
            }
            else
            {
                $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
            }

            if(!$extension)
            {
                $extension = '';
                $file_name = str_replace('.', '', $file_name);
            }
        }
    }

    else if($validation_type == 2)
    {
        if(!in_array($ext, $image_extensions_allowed))
        {
            $exts = implode(', ',$image_extensions_allowed);
            $error .= "<br/><div class='submitEventErrors'>You must upload a file with one of the following extensions: ".$exts."</div>";
        }

        $extension = $ext;
    }

    if($error)
    {
        echo '<font color="red">'.$error.'</font>';
    }

    if($error == "") // No errors were found?
    {
        $new_file_name = strtolower($file_name);
        $new_file_name = str_replace(' ', '-', $new_file_name);
        $new_file_name = substr($new_file_name, 0, -strlen($ext));
        $new_file_name .= $extension;

    }
    else
    {
        @unlink($file['tmp_name']);
    }

} // [END FILE UPLOADED]

1 个答案:

答案 0 :(得分:1)

尝试使用is_uploaded_file而不是 if($ _ FILES!=“”)

这里有更多细节 http://php.net/manual/en/function.is-uploaded-file.php