File upload restrict certain file type
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 sy开发者_如何学运维stem 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
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.
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.
If you only want jpegs then load it with imagecreatefromjpeg which returns FALSE on errors for bogus jpegs.
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.
精彩评论