PHP makes uploading files easy. You can upload any type of file to your Web server. But with ease comes danger and you should be careful when allowing file uploads. In this tutorial we will discuss security issues concerned with the file uploading.
- Check the referrer: Check to make sure that the information being sent to your script is from your website and not an outside source. While this information can be faked, it’s still a good idea to check.
- Restrict file types: You can check the mime-type and file extension and only allow certain types to be uploaded.
- Rename files: You can rename the files that are uploaded. In doing so, check for double-barreld extensions like yourfile.php.gif and eliminate extensions you don’t allow, or remove the file completely.
- Change permissions: Change the permissions on the upload folder so that files within it are not executable. Your FTP program probably allows you to chmod right from it.
- Protecting the upload folder with .htaccess: Another popular way of securing file upload forms, is to protect the folder where the files are uploaded using .htaccess file. The Options -Indexes line in .htaccess would accomplish disabling the indexes.
Options -Indexes Options -ExecCGI AddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi
Disabling executing of these files could give us an extra layer of protection.
Further if you are allowing your users only photos or picturer, you can restrict other files by placing the following code your your .htaccess file.
<Files ^(*.jpeg|*.jpg|*.png|*.gif)> order deny,allow deny from all </Files>
- Place the upload folder outside WWW root: The simple way is to secure your contents is moving your upload folder outside WWW root. In this way the contents of your writable folder will not be revealed to outside public. Remember it is still writeable. Inside your PHP script you can access the folder something like to the folder above your WWW root
- Login and Moderate: Making your users login might deter some deviant behavior. You can also take the time to moderate all file uploads before allowing them to become live on the web.