上传文件0时错误来自php

时间:2013-07-08 07:15:23

标签: php image file-upload

我正在使用PHP上传图片。图片是 .jpg 类型,但在上传时,它会给我错误 0

这是我的代码。

if(isset($_FILES["image_file"]["name"])){
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $extension = end(explode(".", $_FILES["image_file"]["name"]));
    if ((($_FILES["image_file"]["type"] == "image/gif")
    || ($_FILES["image_file"]["type"] == "image/jpeg")
    || ($_FILES["image_file"]["type"] == "image/jpg")
    || ($_FILES["image_file"]["type"] == "image/pjpeg")
    || ($_FILES["image_file"]["type"] == "image/x-png")
    || ($_FILES["image_file"]["type"] == "image/png"))
    //&& ($_FILES["image_file"]["size"] < $size)
    && in_array($extension, $allowedExts))
      {
      if ($_FILES["image_file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["image_file"]["error"] . "<br>";
        }
      else
        {
            $generate_random_number = rand(1,1000);
            $random_image_name = $generate_random_number.$_FILES["image_file"]["name"];
          if (file_exists($upload_dir_path.$random_image_name))
              {
                //echo $_FILES["file"]["name"] . " already exists. ";
              }
          else
          {
            move_uploaded_file($_FILES["image_file"]["tmp_name"],
            $upload_dir_path.$random_image_name);
          }
        }
      }
    else
      {print_r($_FILES);
        echo "Invalid file";
      }

}

运行以下是输出:

Array ( [image_file] => Array ( [name] => Chambers_block_study.JPG [type] => image/jpeg [tmp_name] => /tmp/phpghmfM2 [error] => 0 [size] => 2656165 ) )

文件无效

请帮忙。谢谢!

3 个答案:

答案 0 :(得分:1)

Error 0 means no error,所以一切都应该没问题。如果您遇到问题,则不是由文件上传本身造成的。

附注:要检测JPG图像,最好使用getimagesize()而不是检查扩展名/ MIME类型。这些是由客户设定的,可以伪造。

示例:

$info = getimagesize($_FILES["image_file"]["tmp_name"]);

if ($info == false) 
 {
 echo "Image is not a valid image file";
 // do whatever
 }

答案 1 :(得分:1)

可能是因为它区分大小写:您的数组中有jpg,但文件以JPG结尾 尝试

in_array(strtolower($extension), $allowedExts)

答案 2 :(得分:0)

直接来自PHP manual

UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.

这意味着您的文件已正确上传。

如果用户上传扩展名为.JPG的文件,则if语句将失败。所以我宁愿使用这样的东西来检查图像扩展名:

$image_ext =  strtolower(pathinfo($_FILES["image_file"]["name"],PATHINFO_EXTENSION));

此外,最好使用getimagesize()来检查图像的有效性。您可以按如下方式使用它:

$isImageValid = @getimagesize($image_tmp);
if($isImageValid){
//do whatever
}

希望这有帮助!