Adding a Custom File Handler
Sometimes it is convenient to “fake” a file — the browser has requested a file, but it it needs to be generated or processed before it is sent out.
This can easily be done using a combination of the
.htacces file and PHP.
.htaccess is a configuration file which is read every time Apache serves a file. It allows you to pre-process requests. The configuation is inherited by sub-directories. If a sub-directory also contains a
.htacess file, its settings will combine with or override those of the higher directory.
You can use
.htaccess to dynamically (re)interpret types of files. In this case, we will use it to interpret exactly one file. To do so, we use the
# .htaccess <Files file.ext> </Files>
This indicates that a request for
file.ext will be interpreted or processed. Here, we will rewrite it to call a PHP script:
# .htaccess <Files file.ext> RewriteEngine On RewriteRule ^(.+)$ doit.php [QSA,L] </Files>
- The pattern
^(.+)$roughly means rewrite the whole request.
doit.phpwill be the name of the PHP script to run. You can also include an absolute path, from the web root directory.
[QSA,L]will also pass on any query string which might have been included.
Roughly, the rule means:
That’s it. All you need now is a PHP script to process things.
So, what’s the benefit of this technique? Basically it allows you to generate a virtual file which is really the result of a PHP script. For example:
random.jpgcould be used to return a random image
styles.csscould be used to return dynamically created CSS
news.txtcould be used to return the latest or a random item of news
In each case, the browser requests what appears to be a static file.
Example: Random Image
Here we will intercept a request to
random.jpg go return a random image from a specific directory.
.htaccess file is mostly the same. We will use the name of a notional image,
random.jpg, though it could have been anything:
# /images/.htaccess <Files random.jpg> RewriteEngine On RewriteRule ^(.+)$ /images/random.php [QSA,L] </Files>
.htaccess file is placed inside the
images directory, and the script will be called via
/images/random.jpg. This will, in fact run the script
For the PHP script:
read the file names in a a predefined directory:
Load a random Image:
Send the appropriate header, and output the image:
header('Content-Type: image/jpeg'); imagejpeg($image);
This give us:
<?php $images=glob("$root/images/slides/*.jpg"); $image=imagecreatefromjpeg($images[array_rand($images)]); header('Content-Type: image/jpeg'); imagejpeg($image); ?>