Here's a little something I just put together. Since I'm not sure if anyone's posted on this before, I figured I'd pass it along.
I was looking for a way to pull images out of a database using PHP, which has been described on the site many times. However, here is the catch - I wanted to do it without having something like <img src="img_gen.php?img_id=343"> in my HTML. The reason for this is simple, as some older browsers might choke on a src attribute with a .php extension (even though the HTTP header tells it the file is an image, ie: .gif, .jpg, .png.)
So, I used a ForceType directive in my httpd.conf file to force anything pointing to /gfxdb/... to execute a script called "gfxdb". (ForceType has been discussed elsewhere on this site - do a search for more info.) "gfxdb" parses the REQUEST_URI, pulls out the image id, and then returns the image (with the right header.) The beauty part is that the entire process is invisible to the browser, which thinks it's requesting "/gfxdb/foobar_232.jpg", when it's really asking the gfxdb script to get the image with the id of 232 out of the database. The nice thing about the format I used is that you can change the "foobar" part to denote different directories or whatever, and it will share the same image. So, to a search engine like Google, foobar_232.jpg and barfoo_232.jpg are separate, indexable images, but to your database, they are the same one.
Anyway, here's the code I used. This code assumes you've got the following table in you database, and it's populated.
CREATE TABLE images (
img_id tinyint(5) NOT NULL auto_increment,
img_name varchar(50) NOT NULL default '',
img_size varchar(10) NOT NULL default '',
img_type varchar(20) NOT NULL default '',
img_data blob NOT NULL,
UNIQUE KEY img_id (img_id)
) TYPE=MyISAM;
It also uses PEAR (which you should be using anyway.)
<?
require_once( 'DB.php' );
/ set database vars /
$user="your-user-name";
$pass="your-password";
$host="your-host";
$name="your-db-name";
/ set default image, in case image is not in database /
$default_img_url="your_host/not_found.gif";
/ parse image name out of URI /
$url_vars=explode( '/', $REQUEST_URI );
/ parse img_id out of image name (grabs number between "_" and "." ) /
preg_match("/_(.?)./", $url_vars[2], $matches);
/ set db variables and connect to db /
$db = DB::connect( "mysql://$user:$pass@$host/$name" );
$sql="SELECT img_data, img_type FROM images WHERE img_id='$matches[1]'";
/ display image if it is in database, otherwise use the default image /
if( $img_row=$db->getRow( $sql, DB_FETCHMODE_ASSOC ) ) {
header( "Content-type: $img_row[img_type]" );
echo "$img_row[img_data]";
}
else{
header( "Location: $default_img_url" );
}
?>