Image Upload Code

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

I'm trying to write a decent image upload class. To maintain some sense of security I:

  • Check the Content-Type of the uploaded file
  • Check the mime type of the file (using the results from getimagesize())
  • Check the file extension to make sure it's gif, jpg, png
  • Check the file size
  • Check image size and resize if necessary

Is there anything else you guys can think of that needs to be checked?

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Thats all I check for.

I first use the PHP $_FILES [error] to quickly check for errors for a quick exit if any found, then run some more solid checks as you listed.

I also use a htaccess in the images folder that prevents any scripts running.

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

Checking the filename isn't really necessary if you check content & mime types. I usually recreate the file extension based on the type anyway, for the people that use .jpeg instead of .jpg and .tiff instead .tif.

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

Hidden PHP code in the comments of the gif could be executed if the file extension is PHP. I guess if you recreate the image, those comments might be left out. But I only recreate the image if the image size is too high or wide. And I guess what greg said would prevent that too.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Another note,
If all checks are ok, I use PHP to move the file from tmp to /real_folder and to the name I define, which is always jpg. Then take the new moved file and use Imagick to resize and overwrite the file with the same name.

If it wasn't changed by Imagick then I assume foul play and delete the image. I know that may be considered a bit hit and miss, but I know of people where file upload failed with this technique in place, and after investigating the files most contained JS, the others some other code like Java/ASP.

I guess no way is 100% fool proof, but with all the checks and stopping code execution in the folder they reside I think it's pretty safe.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.