The Netlobo logo - a Nevada desert landscape

PHP File Upload Security

Some tips to help you learn how to handle file uploads securely with PHP

Published Aug 15, 2005 by lobo235
Last updated on Oct 13, 2008

When using PHP to handle file uploads to your server there are a few things you will want to do to make sure the upload is secure. One of the biggest things that comes to mind is to make sure that the uploaded file does not have an extension that could be dangerous. For example, you probably don't want your users to upload files with the .php extension. A malicious user could upload a PHP script that acts as a portal which they can then use to send spam emails so it looks like it's coming from your server. There are many other things they could do if they are allowed to upload .php files so it's a good idea to block them.

In some cases you may want to block users from uploading .html or .htm files because this basically allows them to put their own web page up on your server. They could put links in the .html to naughty pictures or have some link to malicious spyware programs, etc. This page will be on your server and you could be held responsible for any problems that arise because of it.

Probably the safest thing to do is have some type of moderation system where you (or some other moderator) has to approve the files before they show up on the site. In order to implement this you would want your file to be moved to an area where site visitors could not access it and then check the file out yourself. If the file is harmless you can then post it to the public area of the site. This can take up large amounts of time depending on how many files you receive through your upload script. I find it best to use a combination of moderating uploads and blocking certain file extensions. By blocking extensions such as .php and .html you will already have less moderating to do.

You must also be careful though because someone could easily change the extension of the file allowing them to upload the file. For images, you can check the image header to determine the image type. This way you don't have to rely on the file extension.

I hope these ideas will help you when you setup a PHP file upload script. Implementing the above features into my own scripts has saved me a lot of grief. Please let me know if you have any suggestions to improve this article. I am open to your feedback.

0 comments for this article.

del.icio.us logo add this article to del.icio.us! Other great Web Development and Programming articles on Netlobo.com:
Clear File Input Using Javascript
Javascript window.close Example
How to Decrease Load Time of your Web Pages