Alternate Automatic Include File

A week ago I wrote a post on how to easily, and automatically include files on your website using the Apache module php.modc. Unfortunately, not all we3b hosting providers have this module switched on, and don’t allow you to change this. Luckily there is a workaround involving the RewriteEngine.

The idea is simple: redirect all requested pages of the defined extensions to a specified file, and in that file, include the requested page. Below is what the .htaccess script will look like. In this case, prepend.php is the file that is included, and it’s located on the root directory of the website.

1
2
3
4
RewriteEngine On
 
RewriteRule ^prepend.php$ - [L]
RewriteRule \.(php|htm|html)$ /prepend.php [E=FILE:%{SCRIPT_FILENAME},L]

In the file you redirect to, simply include the requested file.

1
include($_SERVER['REDIRECT_FILE']);

Sometimes, depending on your server settings, REDIRECT_FILE may not be the correct server variable. To figure out which one, change your apache code and php file to the following.

1
2
3
4
RewriteEngine On
 
RewriteRule ^prepend.php$ - [L]
RewriteRule \.(php|htm|html)$ /prepend.php [E=FILE:THIS_IS_IT,L]
1
print_r($_SERVER);

Now, just go to a page that would include the file, and all the server variables will be printed. Find the one who’s value is THIS_IS_IT, and bingo, there’s your variable! :-O

Simple as that!

September 11th, 2009 | Apache / PHP

Leave a Reply

Name:
Email:
Website:
Message:
SUBMIT