开发者

How to prevent unwanted files when a website offers image upload using PHP?

if ((($_FILES["uploadedfile"]["type"] == "image/gif")
|| ($_FILES["uploadedfile"]["type"] == "image/jpeg")
|| ($_FILES["uploadedfile"]["type"] == "image/pjpeg"))
&& ($_FILES["uploadedfile"]["size"]/1024<100))

When I test the code above, I found that a user can bypass the f开发者_JAVA技巧ile type check by simply modifying the extension name, how to get the real file extension name?

Also, when a user uploads a very large file, how to immediately reject the upload on the server side?


you cannot really accurately get the file type from the mimetype since it's an user input and could be easily forget. What you can do is to use the file command on *nix to make sure it is a real jpeg or gif files. On the same fashion you can try to load it with GD (image extension) or Image magic.

an example of file output

olivier@olivier-laptop:~/trust/public/images$ file verisign_sample.gif 
verisign_sample.gif: GIF image data, version 89a, 100 x 60

using the backtice operator you would be able to get the result and parse it

$line = `file $filepath`

For your second question it depends on the browser,in the RFC the browser don't have to supply the content size when making the request, so you cannot stop the upload if the file is very large. It will upload until it reaches your PHP upload limit(upload_max_filesize parameter of php.ini) and PHP would kill the request.


Indeed, a user can bypass the file check by modifying the file extension. You can't rely on anything that is contained under either "name" or "type" in $_FILES, as these can both be user-supplied, therefore meaning that can definitely not be considered trustworthy.

As RageZ pointed out, you can use the file command for determining file type, or try loading the image with GD or something similar. You can also look at the file header yourself: there is an interesting article on doing this here


If you want to provide only image uploads, you check for the file type by using getimagesize() and then image_type_to_mime_type().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜