PHP File Upload Security

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.

  1. 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.
  2. Restrict file types: You can check the mime-type and file extension and only allow certain types to be uploaded.
  3. 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.
  4. 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.
  5. 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
  6. 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
    <img src="./uploads/photo.gif>
  7. 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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s