InternotesSharing Web Development Techniques

Blossoms

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.

The Technique

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 Files directive:

#   .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.php will 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: file.extdoit.php

That’s it. All you need now is a PHP script to process things.

The Benefits

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.jpg could be used to return a random image
  • styles.css could be used to return dynamically created CSS
  • news.txt could 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.

The .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>

Here the .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 /images/random.php.

For the PHP script:

  • read the file names in a a predefined directory:

    $images=glob("$root/images/slides/*.jpg");
  • Load a random Image:

    $image=imagecreatefromjpeg($images[array_rand($images)]);
  • 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);
?>