When building an application that uses images uploaded from users, one of the most important issues is making sure the uploaded file is a valid image file and that it does not contain hidden scripts inside it that could be harmful. I was wondering whether anyone knew of the best way to secure image file uploads. One way would be to check the file type through the files array provided by php: $_FILES['userfile']['type']. However, it is clearly stated that this is not reliable. Another way would be to check the file extension. This too will not do the trick, b/c executable php files can be masked as image files with appropriate extensions such as gif or jpg. Developers sometimes think that validating an image using the php getimagesize function will do the trick. This method too will not work b/c executable php code can be inserted into the image description causing the image to pass the getimagesize validation while still containing harmful code. I'd just mention that in this respect, that the attacker must be able to find the uploaded file in order to use it. Changing the image file name is therefore a must, if one wants to be protected against such attacks. So it seems like none of these methods alone will do. Actually, it doesn't seem like using all of them will completely secure your application. I was wondering whether someone knew of better ways to secure image file uploads. This is a common feature and I am sure there are many methods of securing this process. Please share your thoughs.
getimagesize is indeed the best available option, and ofcource naming the files with a NON executable extension.
Some server side software can be used that checks a file and returns whether it is an image file or not.
Hmm.. For my sites, I always check the extension and do the appropriate ImageCreateFrom___ function based on the extension and see if it returns false or not (never thought of just running getimagesize). I don't really know what else you could do if people can still get passed these checks with other methods..