views:

59

answers:

2
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 file 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?

+1  A: 

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.

RageZ
Use the file command on *nix to make sure it is a real jpeg or gif? What do you mean? What does GD mean? Also can I set the PHP upload limit?
Steven
What if a user upload a virus or Trojan horse?
Steven
on linux the is a file command, this command try to guess what is the type of passed filename. for example the output of `file verisign_sample.gif` would be `verisign_sample.gif: GIF image data, version 89a, 100 x 60`
RageZ
GD and image magick are libraries to manipulate image file (PNG, Gif, Jpeg), if you are not able to load those file with GD function it must mean it is not a proper jpeg/gif file.
RageZ
A: 

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

gab