Check picture file type and size before file upload in php

后端 未结 7 1572
走了就别回头了
走了就别回头了 2020-12-09 13:41

I have the following code:

$filecheck = basename($_FILES[\'imagefile\'][\'name\']);
  $ext = substr($filecheck, strrpos($filecheck, \'.\') + 1);
  if (($ext          


        
7条回答
  •  眼角桃花
    2020-12-09 14:11

    File size is fairly obvious, but what people are doing above to check that it's the right format is somewhat inefficient, and "unsafe".

    Here's what I do:

    if($_FILES["userPicture"]["error"] == 0) {
    // File was uploaded ok, so it's ok to proceed with the filetype check.
        $uploaded_type = exif_imagetype($_FILES["userPicture"]["tmp_name"]);
        // What we have now is a number representing our file type.
    
        switch($uploaded_type) {
            case "1":
                $uploaded_type = "gif";
            break;
            case "2":
                $uploaded_type = "jpg";
            break;
            case "3":
                $uploaded_type = "png";
            break;
        }
    }
    

    More info at;
    http://www.php.net/manual/en/function.exif-imagetype.php

    Edit: This has the advantage of working "in every browser" because it doesn't rely on the filename, or anything user supplied, except the files array value "error" which tells us there wasn't really an error.

提交回复
热议问题