Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload restrict certain file type

Tags:

php

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

like image 381
teepusink Avatar asked Jan 26 '26 06:01

teepusink


1 Answers

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.

like image 185
Lightness Races in Orbit Avatar answered Jan 28 '26 19:01

Lightness Races in Orbit