简体   繁体   中英

PHP files type checking

Some weird case when I tried a simple php code to check the file type and it couldn't pass through. Any mistake from the below code ? Thanks in advance.

if(($_FILES["file"]["type"]!="image/jpeg")||
            ($_FILES["file"]["type"]!="image/gif")||
            ($_FILES["file"]["type"]!="image/png")){
            echo "File must be in format of jpeg,gif or png.";
        }

"Not a JPEG", "not a GIF", "not a PNG" . At least two of these conditions have to be true . Since you're using || , if any of these is true , the whole if condition is true .

You're looking for "is not JPEG and is not GIF and is not PNG" .

Apart from that, you can use the much more succinct form:

!in_array($_FILES["file"]["type"], array('image/jpeg', 'image/gif', 'image/png'))

Also, the $_FILES["file"]["type"] is user supplied information which you shouldn't trust. You should try to figure out the MIME type yourself from the file itself. For example, see How to get the content-type of a file in PHP? .

mime_content_type('php.gif')将输出图像/ gif

Your conditionals are wrong, you want "&&" rather than "||". Also, $_FILES["file"]["type"] is the type as reported by the browser, so it may well be incorrect or missing. Have you tried logging it to see what exactly the browser is sending?

You'd be much better served by using FileInfo or the like to check the type, or seeing if GD or another image processing extension accepts it.

I would prefer getimagesize() to avoid problems with the mime-types, especially of JPEGs, where are a lot of mime-types are possible.(As Anomie wrote $_FILES["file"]["type"] is the type as reported by the browser).

Try it, take some exotic filetype and give it an extension like .gif or .jpg.

$_FILES["file"]["type"] will report something like 'image.gif' or 'image.jpeg', but getimagesize() will return false , because it detects that the file is not an image.

This can be used to upload eg PHP-scripts onto the server.

Also note: never trust any uploaded file, images may be correct but can also contain PHP-code inside comments. So be sure that those images never can be included by any PHP-script on your server.(additionally you could check the image for PHP-code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM