Main Content

Using PHP to upload images / Store on MySQL database - security questions

Archive - Originally posted on "The Horse's Mouth" - 2007-10-19 08:03:26 - Graham Ellis

Yesterday, the page on our website that shows you how to upload an image from a browser in a PHP script, store the image in a database, and later on retreive and redisplay the image, was visited 250 times. Not bad for such a specific subjec t on what I'll admit is something of an obscure web site.

One of our 250 visitors wrote to me - an excellent question - concerning security issues with such uploaded images - "How do you secure such uploads? I mean, i changed the extension of a .exe file as .png and uploaded without any issues. I do realize that the image will not be displayed. But in theory the file is still located in the filesystem. Wouldn't this mean someone can upload a trojan or infected file and mess up the entire server?"

He's 100% right to think carefully about the validity / checking of what can be uploaded through scripts such as this. Yes, they can be used for ANY "blob" of data - any bit patterns at all, including all sorts of nasties. That's not just limited to trojans and infected files as you suggest, but also includes copyrighted images, pornographic pictures, and images of text which makes illegal statements / claims. And I'm sure you could find other things too.

But if the data is held in the database AND ONLY RECALLED / USED AS AN IMAGE, then it is not messing up the whole server - it's not being run in any way. If the .jpg standard allowed for the embedded execution of code that it would be a problem as you suggest, but to my knowledge that's not going to be the case. If my server script that recalled the file said "if it looks like an executable, go run it" that would be a problem ... but it does not. All it does is sends out the image, labelled as a .jpg, to a browser.

The uploading of images that should not be uploaded (copyright, etc,) is a more difficult matter to answer. And it's really the same question that anyone who has a web presence onto which public data uploads is accepted has to be aware of and think through. In the case of our demonstration, we have many people trying out the scripts and so any image which really should not be there quickly sinks into the obscure depths and is no longer accessible, so the system is in effect self-cleansing. For a live web site where the purpose is publication, you need to look at other measures such as having moderator presence, an acceptable user policy, a way of reporting abuse, perhaps an automated spam trap, and more.

More links:
Try out the upload script
View recent uploads
Source code listing