Tuesday, January 08, 2008

base href does not work for php includes !! (and what to do about it)

Base href is very handy for organizing relative addressing on a website. You may, for example, be working on a project for a client with a directory structure like this:


The 'normal' root of this would typically be www.userexperiencedesign.co.uk but if you want the /cambridge_motorcycles part to be the root, you could define a base href so that all the sub-directories under it would refer to that as root instead. Like this...

<base href="http://www.userexperiencedesign.co.uk/projects/cambridge_motorcycles/\" />

This works GREAT for images and general relative addressing.

I was stumped for a while, trying to figure out why this didn't work for PHP includes. PHP experts would not be so stumped. PHP is handled server side, so the base href in the document is not used. After a lot of head scratching I figured that you could define an equivalent for base href to be used by the PHP includes.

First, you need to define the variable in PHP. Mine is like this...

<?php $root="http://www.userexperiencedesign.co.uk/projects/cambridge_motorcycles/\"; ?>

Then, when you call the include file you do it like this...

<?php include ($root."include/header.html\"); ?>

This gives us a neat way to fake up a base href equivalent for PHP includes. Neat!

If you are an efficiency expert you might worry about how many server calls are made by the PHP includes and whether, when defining $root, you should give the whole path or something relative. My sites are very small so this is not a big deal for me but if anyone wants to leave comments on efficiency (or anything else) I am always happy to learn!


webado said...
This comment has been removed by the author.
webado said...

Careful! This will be invalid in many Apache installations, where you are not allowed to include external files.

You may have to determine the full path relative to the home directory, perhaps:

$root ="/home/userid/public_html/";

depending on installation.

Then you can prepend that to the script's own path and name.

include ($root."include/header.html\");