Recipe 8.7 Invoking a CGI Program for Certain Content Types

Problem

You want to invoke a CGI program to act as a sort of content filter for certain document types. For example, a photographer may wish to create a custom handler to add a watermark to photographs served from his web site.

Solution

Use the Action directive to create a custom handler, which will be implemented by a CGI program. Then use the AddHandler directive to associate a particular file extension with this handler:

Action watermark /cgi-bin/watermark.cgi AddHandler watermark .gif .jpg

Discussion

This recipe creates a watermark handler that is called whenever a .gif or .jpg file is requested.

A CGI program, watermark.cgi, takes the image file as input and attaches the watermark image on top of the photograph. The path to the image file that was originally requested in the URL is available in the PATH_TRANSLATED environment variable, and the program needs to load that file, make the necessary modifications, and send the resulting content to the client, along with the appropriate HTTP headers.

Note that there is no way to circumvent this measure, as the CGI program will be called for any .gif or .jpg file that is requested.

This same technique may be used to attach a header or footer to HTML pages in an automatic way, without having to add any kind of SSI directive to the files. This can be extremely inefficient, as it requires that a CGI program be launched, which can be a very slow process. It is, however, connstructive to see how it is done. What follows is a very simple implementation of such a footer script:

#! /usr/bin/perl print "Content-type: text/html\r\n\r\n"; my $file = $ENV{PATH_TRANSLATED}; open FILE, "$file"; print while <FILE>; close FILE; print qq~ <p> FOOTER GOES HERE ~;

The requested file, located at PATH_TRANSLATED, is read in and printed out, unmodified. Then, at the end of it, a few additional lines of footer are output. A similar technique might be used to filter the contents of the page itself. With Apache 2.0, this may be better accomplished with mod_ext_filter.

See Also

  • Recipe 8.10

  • Recipe 10.7



Apache Cookbook
Apache Cookbook: Solutions and Examples for Apache Administrators
ISBN: 0596529945
EAN: 2147483647
Year: 2006
Pages: 215

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net