Blocking PHP execution in writable directories
How to prevent malicious scripts from running in vulnerable folders on your site.
One of the most common ways a site gets compromised is through PHP shells — malicious scripts that an attacker uploads to your server and then uses to modify files, read configuration data, or gain direct access to your database.
The catch is that shells can only be uploaded to directories that are writable. So if a folder doesn't need to execute PHP — and most upload and media folders don't — you should explicitly disable it. The usual suspects are directories like /images/, /uploads/, /templates/, and anything else where user-uploaded content lands.
Method 1 — CGI, FastCGI, suPHP, or DSO (Apache) servers
Create a .htaccess file in the directory where you want to block PHP execution. If one already exists, add the following to the top of it:
<FilesMatch "\.([Pp][Hh][Pp]|[Cc][Gg][Ii]|[Pp][Ll]|[Ph][Hh][Tt][Mm][Ll])\.?.*">
Order allow,deny
Deny from all
</FilesMatch>
This blocks direct HTTP access to any PHP (and CGI/Perl/PHTML) files sitting in that directory. Even if a shell gets uploaded, it can't be executed through the browser.
Our products and services
Method 2 — mod_PHP servers (DSO — Apache PHP)
If your server runs in mod_PHP mode and allows php_flag and php_value directives in .htaccess, this one-liner is all you need:
php_flag engine off
Drop it into a .htaccess file in the folder you want to protect. This completely disables the PHP interpreter for that directory and every subdirectory beneath it. Any PHP file uploaded into that tree becomes dead weight — the server simply won't run it.
Help
If you have any questions or need assistance, please contact us through the ticket system — we're always here to help!