Executing PHP scripts in a Drupal site

Other than running this blog, I also test PHP codes on this server. If you are running Drupal on an Apache web server, then Drupal’s .htaccess file is configured to disallow access to any folders that does not belong to Drupal. This means that if I need to create a folder of my own to execute PHP codes, Drupal’s .htaccess configuration will stop me and show this nice 404 page. 

This is a nice and elegant if you setup your server for the sole purpose of running your website in Drupal. Unfortunately this doesn’t quite work for me because I sometimes need to run things like this. Here’s a documentation of how I edited the .htaccess file to do it.

Editing .htaccess

Look for this chunk of code in your .htaccess file.

# Pass all requests not referring directly to files in the filesystem to
# index.php.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

Add this just before the line that says “RewriteRule ^ index.php [L]“, assuming that the folder that you wish to allow php codes to be executed is /codetest. This tells your web server to ignore /codetest when it attempts to hide everything that isn’t part of what viewers should access.

RewriteCond %{THE_REQUEST} !/codetest/.*

And then look for this chunk of code in your .htaccess file.

RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$ 

And add the following right after. This tells your web server that it needs to let any files with the extension .php execute the way it should.

RewriteCond %{REQUEST_URI} !/codetest/[^/]*\.php$

And there you are! Special thanks to the folks here for some of these instructions.

Photo by Chris Ried on Unsplash