开发者

Detect if uploaded file is an image in PHP

How do I detect if an uploaded file is an image开发者_如何学Python using PHP?

I do not want to use imagesize() or check on the file extension.


Don't be silly, use a tool especially made for this purpose - getimagesize()


You could use the ImageMagick identify tool to obtain information on a wider variety of image formats than getimagesize() supports, e.g.

$uploaded=$_FILES["myfile"]["tmp_name"];
$info = `identify $uploaded`;

Here's some sample output for a JPEG

img029.jpg JPEG 1240x1753 1240x1753+0+0 8-bit PseudoClass 256c 27.3KiB 0.000u 0:00.000


If you are talking about images that are going to be displayed in the browser, and you want to make as sure as possible they are valid images, I recommend opening them in GD using the appropriate imagecreatefrom*() function and saving them back in the desired target format.

That not only makes sure they are images - this won't work if the input data is broken - but it also filters out any possible shenanigans exploiting leaks in the browsers' graphics libraries, and removes Metadata contained in the image (which often contains sensitive info like author, program(s) used to create the image, camera, location and shooting time) and makes sure the image can be viewed in the browser (CMYK JPG uploads, which will not display in any Version of IE, won't work.)

A potential downside of this is that JPEG images may suffer from a slight loss of quality (GD's JPG encoding quality is not good) and there may be problems with images with transparencies.


You can use mime_content_type and verify the types of the uploaded file. Since mime_content_type is deprecated you can use its alternate finfo_open.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜