Securing PHP application from malicious scripts

If you’ve stumbled across this post, then you’ve recently become a victim of the most famous way of uploading a malicious script to a website – PHP file uploads.

Many websites and web applications that are developed using PHP & MySQL allow users to upload files, photos and documents to the server. Normally, the upload script receives the files and moves (or writes) it to a directory (folder) with write permissions. If you are on Linux, then this would mean that your folder CHMOD value is 0777.

The Problem
The changing of CHMOD value to 0777 practically allows anyone in the WORLD to write to your folder and is therefore not recommended. However, many a times we are left with no option but to do so – depending on the servers’ environment.

How can this be a problem?
This allows attackers to upload upload a malicious PHP script to your directory, which they will then execute by accessing it. This script could either be a mass-mailing script or a malicious script to gain access to your account (or web server).

The Solution
It is said that prevention is better than cure – and therefore, it is important to prevent these scripts from being executed by the server. This can very simply be done by adding a few lines of code to your .htaccess file. If your directory is supposed to hold photo files only, then the following code is recommended to prevent scripts from being executed.

It is also important to disable directory listing on these folders.

# Disable Directory Listing
Options All -Indexes

# Allow access to these file extensions only
<FilesMatch ".(htaccess|htpasswd|ini|php|cgi|pl|phps|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

The above will add an extra layer of security to your web application.