1

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.";
        }
1
  • You have enctype="multipart/form-data" in your html form right? If yes and you can print_r $_FILES then look for answer what @deceze gave. Commented Apr 10, 2011 at 2:08

4 Answers 4

5

"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?.

Sign up to request clarification or add additional context in comments.

Comments

1

mime_content_type('php.gif') will output image/gif

1 Comment

thanks for remind me about the type being check using mime as deceze mention this too. Thanks guys.
1

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.

Comments

0

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 e.g. 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.