Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a safe file upload script in php?

i check the file for its extension, and mime type - is there anything else i can be doing to help make file uploads safer?

its for an avatar (so all the images are in one folder). i was thinking about using htaccess to forbid any php execution just incase some php file found its way in there. what do you think?

like image 276
phpuploader Avatar asked Nov 29 '09 16:11

phpuploader


2 Answers

Neither file extension nor mime type can give you 100% security that you are dealing with a image file. But as long as you're not going to execute the file (e.g. by using include()), that is not a problem and you do not need to check for PHP code or anything else. The only security breach imaginable using a forged image file would be something that exploits the browser's rendering engine. This is impossible to protect effectively against from server side and is the browser vendor's responsibility.

So, as long as you make sure you use is_uploaded_file() and move_uploaded_file() when handling the upload, you should be fine, at least on the image format front. Make sure you read @bobince's post below and follow the link, it contains a bunch of great information on other security aspects when dealing with files.

You could however, to provide totally maximum security, of course copy the image into a new image container using GD's imagecopy. This would erase any ID3 and other header information contained in the file, and probably destroy any exploit attempts (GD would probably choke on such a file and return an error). This works for GIF, JPEG, and PNG only, of course, and you may run into some issues like alpha channel and colour profile problems.

like image 109
Pekka Avatar answered Sep 20 '22 23:09

Pekka


  1. Never use user-submitted filenames at all; make up new ones like «random number».jpeg. ‘Sanitising’ filenames is harder than you think, especially if the app needs to be able to run on a Windows server.

  2. For images, use the PHP getimagesize function to determine the filetype of an image, rather than looking at the highly-unreliable filename and mimetype submissions. Disallow uploads that don't parse as images.

  3. For files that are intended to be downloaded, use the Content-Disposition: attachment header to stop IE sniffing for HTML content and displaying it in the browser.

  4. For files that must display inline you'll have to serve them from a different hostname to your main site, otherwise HTML content inside them can cross-site-script into your security context.

Making a file upload feature secure is hard. More discussion.

like image 29
bobince Avatar answered Sep 19 '22 23:09

bobince