Downloads

 

Trick: Image Uploads

We have all written scripts to upload files to a server, and for one reason or another I find that most of the time the script is intended for image uploads. Whenever you are uploading user files to the server it is very important that those files are validated to ensure the uploaded file is actually what is expected. Since just checking the HTTP headers and the file’s extensions is insufficient we need to find another way to determine if the file is actually an image file.

While writing some validation code I came across this “trick” which can be used to determine if a file is an image file: Send the uploaded file through getimagesize() and check the return values.

As the PHP Manual states:

PHP Manual

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTP content type.

If PHP cannot access the file or the file is not an image, the function will generate an E_WARNING error, and return boolean FALSE. The E_WARNING error can be suppressed by using the error suppression operator ‘@’. As long as you know that the file is accessible to PHP (which it should be if PHP uploaded the file) and the function does not return FALSE, then you have a valid image file.

I first leaned about this method from the book php|architect’s Guide to PHP Security by Ilia Alshanetsky.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Improve the web with Nofollow Reciprocity.