3

I'm doing a file upload script that only allows jpgs.
The script that I'm using to check is

$size = getimagesize($filename);
$size['mime'];

That works in most cases. However, if I have a "gif" file and I renamed the extension to "jpg", it tricks the system since the mime type for that file shows up as jpg.

How can I prevent that?

So jpg and png are allowed Gif is disallowed

4 Answers 4

3

Instead of $size['mime'] (which, as you have realised, is the MIME-Type and thus not entirely reliable), use $size[2].

The manual entry says that it contains

one of the IMAGETYPE_XXX constants indicating the type of the image.

A comment further down the page conveniently lists those constants:

 1 = GIF
 2 = JPG
 3 = PNG
 4 = SWF
 5 = PSD
 6 = BMP
 7 = TIFF (Intel byte order)
 8 = TIFF (Motorola byte order)
 9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM

This information is generated by examining the file itself and, as such, is the most reliable mechanism at your disposal.

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

1 Comment

@leonbloy: Aha, there it is! Thanks.
1

However, if I have a "gif" file and I renamed the extension to "jpg", it tricks the system since the mime type for that file shows up as jpg.

Extract the file base name (without extension) using pathinfo():

$file =
 pathinfo("myFakeGifImage.jpg", PATHINFO_BASENAME); // returns myFakeGifImage

and add the extension based on the file type that getimagesize() returns, not what the user tells you.

1 Comment

I don't understand what removing the extension will accomplish, other than making the $file variable useless for actually accessing the file.
0

If you only want jpegs then load it with imagecreatefromjpeg which returns FALSE on errors for bogus jpegs.

Comments

0

PHP is also able to detect the MIME Type of a file, i.e. by using mime_content_type. This is a safe method since it actually inspects the file's contents.

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.