Manage Your Content With PHP

In this article, we’ll build a simple, template-driven site that separates style, content, and structure in your website. We’ll create a cross-browser stylesheet switcher that remembers the user’s preferences, touching on php variables, cookies, if statements, and including pages with require_once.

Article Continues Below

Separating style, content, and structure#section2

The separation of style from content has become the bugbear of the HTML developer. Traditionally, we’ve used well-written CSS and XHTML to achieve this separation, and we’ve seen how much easier it is to update our sites or provide multiple styles when we write our markup this way. By adding some very basic
PHP to this mix, we can take this modularity a step further, making it easier not only to update our styling, but our structure as well. In essence, we can create our own basic Content Management System.

PHP is an open-source server-side language. In order to use PHP, you will need the PHP module installed on your server. Most Linux servers have this module installed, and the PHP module is also available for Microsoft servers. If you are unsure about your server or modules, just ask your web host.

Essentially, the master template will use XHTML for structural markup, CSS for style, and some basic PHP to manage it all. Some very basic work with PHP variables will give us multiple style sheets, and will allow us to display different content documents within the same template. Since PHP is a server-side language, all the fancy work is done at the server, before the browser ever gets a peek, so this approach makes cross-browser support much easier to acheive.

Client-side languages like JavaScript do their work on the client—the browser—so the success of a page built with JS depends on the quirks of the individual browser. Since the browser never sees any PHP, just the flat XHTML results of the PHP, we don’t have to worry about a browser supporting PHP.

We’ll use a fairly typical site structure: menu + content.

Start the page as you would any HTML page: build the “<html>… <head>…</head>… <body>…” shell, and within the body set out your div tags to identify the structure of your document.

<div class="body">
<div class="menu">


Now we’ll use some basic PHP to include the content. require_once ‘includes and evaluates the specified file during the execution of the script’. In other words, it inserts another file into the document and evaluates the contents of that file for any scripts. The once aspect is a safeguard to ensure that we don’t include the file multiple times, which can cause problems like resetting our variables.

However, require_once() only works in the more recent versions of PHP, so if you have a module older then PHP4 installed on your server, you would need to use include() or require() instead.

<div class="body">
<?php @ require_once ("body.html"); ?>
<div class="menu">
<?php @ require_once ("menu.php"); ?>

Placing the @ symbol before require_once suppresses any error-messages that might be triggered in the included file. You see, PHP has some default error-messages, which can be incredibly useful during development. However, they’re not the sort of thing we often want our users to be staring at. By inserting the @ symbol before a function, we can suppress those error-messages. In many cases, custom error handling would probably be the best solution, but for this article we’ll keep it simple and just suppress them.

Since we are using PHP in this file, we have to save it as a PHP document, so let’s save it as template.php. You may have noticed that menu is also a PHP document, while body is an HTML document. This is because menu is going to parse some PHP variables, while
body will be nothing but text.

Now we have a page that calls in two separate documents, menu.php and body.html, and inserts the contents of those files into the page before showing it to the browser. Since these two files will be included within the body of this existing shell, there is no need for <html> <head> or <body> tags in these two files—just pure content.

Switching content with PHP variables#section4

So far, we have separated the structure of our template from the content that will be inserted into that structure, but as everything is hard-coded, this is still a static page. Some basic PHP variables will allow us to use this single structure as a template from which we’ll call different content files. If you
want to change the structure of your site down the line, you need only update this one document, and your entire site will reflect those changes.

Let’s say we’re building a site about French Communists. We want the basic structure and design to remain the same, but we want to include different chunks of content depending on which communist the user wishes to learn about. So, rather than have two separate pages with redundant markup and structure (babeuf.html,
and picasso.html), we use one master PHP document to host the separate chunks of content.

The menu will stay the same for every page, so we can keep the menu.php hardcoded, but as the body will be changing we’ll need to use a variable to give us a way to reference these changes dynamically.

PHP variables can be identified by their preceding $. So, we can change the hard-coded body.html into a dynamically updateable variable by coding it as $page.html. Every reference to $page will be replaced by whatever we set the variable $page to be.

Change the body reference to:

<div class="body">
<?php @ require_once ("$page.html"); ?>

We’ll set the variable in the query string (everything that comes after the “?”) of the url: template.php?page=babeuf.

The code above will replace any instance of $page with babeuf, so $page.html becomes babeuf.html. If we want to call picasso.html into that same template, we would set the Picasso link in our menu to template.php?page=picasso.

Along this line, if you run a blog, you can set your blog to output nothing but content, and build a PHP shell that will insert the proper page. This will give you one page of structure and markup in which all the different archives can be included. template.php?page=blogger or template.php?page=2002_02_01_archive. Redesigning your site involves updating one PHP page and your style sheets, and every archive will be updated automatically. (Ed. – See ALA’s Slash Forward to find out how to use mod_rewrite to create user-friendly URLs in just this sort of situation.)

Minimizing included pages#section5

Creating a system that assembles our final document out of several pages enables an extremely modular site, but each require_once() requires a little extra time on that server, as we load another separate file into our document. So, it is always a good idea to keep the number of included pages down to a minimum. Since menu.php is hardcoded — it never changes as we always ask for the exact same file — we actually could just enter our menu directly into the template. That would save one require_once, gaining the time the server would spend locating and inserting the appropriate document.

We could achieve more flexible results with a database query while limiting the number of separate calls, but to maintain the simplicity of this example, we’ll keep it as is for this article. Besides, I am still frightened of databases.

There is always a balance between ease of code and ease of maintenance, and between speed of coding and speed of loading. As always, test different versions in multiple circumstances to find what works best for your site, and don’t be scared of databases.

Anyway, now we’ve got a single page for structure, which can include many different chunks of content. You refer to the style sheets as you would any other XHTML document, from within the <head> of template.php.

Switching style with PHP variables#section6

But what if we want switchable styles as well as content? To do this with PHP, we’ll just use another PHP variable; let’s call it $style. In the head of template.php, add:

<?php echo "<style type="text/css" 
"$style.css";> </style>"; ?>

echo functions a lot like JavaScript’s document.write(), writing everything between the quotes into the source of the document. Since the content we are writing into the source contains quotation marks, we need to let the server know which quotation marks we want it to write as punctuation, and which ones are there to identify the stuff we’re printing. Typing a before the quotation mark will make the server print the quotation mark as a quotation mark.

So, if we set the variable style to “default” in the query string like this: template.php?page=babeuf&style=default, the code above
will print out:

<style type="text/css" 
"default.css";> </style>

We can change styles on the fly by changing the variable style so that it will match to an alternative style sheet (template.php?page=babeuf&style=print). And since all the busywork is happening on the server, these alternate style sheets will function on any browser that supports CSS.

Note that the raw ampersand (as in page=babeuf&style) is not standard XHTML, so before you upload your files, be sure to global replace every instance of & with & within links. It will still render properly in the links. For clarity’s sake, I will keep the ampersands raw in this tutorial (as I do while I code as well), but remember to encode them before uploading. The exception to this rule is for instances that never reach the browser, like redirects, but we will cover that later.

However, there is a shortcoming to this solution. Since we do all this style sheet manipulation with PHP variables, the browser has no idea that there are alternate style sheets. In other words, the Mozilla menu option for switching style sheets will show the current style sheet as the only option.

As the other browsers will soon follow suit to offer this feature, and as this is the W3C-suggested method for using alternative style sheets, let’s alter our code so that it will work nicely with future browsers, without sacrificing compatibility with the old ones.

Add the following after the existing style sheet reference:

<?php echo "<link 
rel="alternate style sheet" 
href="print.css" title="Printable" />"; 
<?php echo 
"<link rel="alternate style sheet" 
href="default.css" title="Default" />"; 

Now we have a cross-browser style sheet switcher that takes advantage of the latest alternate style sheet features as well. If we set the $style variable as well as the $page variable in each query string in menu.php, then the user’s selected style will be maintained throughout their visit.

For instance, the link in to the section on Babeuf would be:

<?php echo "<a href="template.php?page=babeuf&style;=$style">babeuf</a>"; ?>

This parses the existing $style variable as well as the new $page, keeping the style consistent while changing the content.

If we wanted to maintain the content and just change the style—say, to a printable version—then we’d do the opposite, maintaining the content by passing the existing value for $page, and changing the value of $style.

<?php echo "<a  href="template.php?page=$page&>
Printable version</a> "; 

Saving the preferred style with PHP cookies#section7

You can even maintain the selected style between sessions with a PHP cookie. PHP cookies are incredibly easy to set. The basic format is:

setcookie ("cookie name", "cookie value", time()+how long you want the cookie to last);?>

So if we want to set a cookie called “styleCookie” that stores the user’s selected style (the $style variable), we would type the followingat the very top of template.php:

setcookie ("styleCookie", $style, time()+40000000);

This will save a cookie called “styleCookie” on the user’s computer with a value of whatever $style is currently set to, and keep it there for a little over a year.

When the user returns to the site on another visit, we need to pull up that cookie and set $style to that value. The easiest way to do this is with a redirect page. Even if you don’t want to mess about with cookies, it is a good idea to use a redirect page if you want users to get to this page from the root of your site. Without a redirect page, in order to reach the Babeuf page hypothetically sitting at, the user would
have to enter

That’s quite a url-ful. So if we save a redirect page at index.php that sends the user to this url + query string, all the user needs to type to access the proper page is

PHP redirects#section8

A straightforward PHP redirect would look like this:

<?php Header ("Location:"); 

Note that as this PHP is never read by the browser, we can keep the & raw, and it will still validate as XHTML. In fact, if we change it to &amp; the server will choke. So, in any case where the browser is doing the parsing (as in <a>), it is okay to switch the &
to &. When the server is parsing it without the browser, keep it raw. If you’re confused by this, a little trial and error with the XHTML validator will clear things up.

Also note that as this is not an XHTML page, we don’t need the typical <body> <head> structure; a file containing nothing but the redirect will do just fine.

The cookie parser#section9

If we added a cookie parser at the redirect page (index.php), it would look like this:

<if ($styleCookie == "") { < $
<else { < $
<}<Header ("Location:;=$style");<?>

if statements in PHP are very similar to if statements in JavaScript or ActionScript. The basic format is:

if (this is true) {
then do this
else {
otherwise do this

In our case, we first need to check if $styleCookie equals nothing (it hasn’t been set).

if ($styleCookie == "") { 

If the cookie doesn’t exist (the user has never visited before or prefers not to accept cookies), then we set the style to default:


If the cookie does exist (it doesn’t equal nothing), then we set $style equal to the $styleCookie:

else {

Regardless which if statement was parsed, $style now has a value, so we can use the same redirect to bring us to the appropriate page:

Header ("Location:

This index/ redirect document declares the default values for all of our variables if they have not already been set. But just in case someone manages to bookmark the template page instead of the index/redirect, we really should declare default values in our template as well. That way, if some calls template.php directly, without specifying any variables in the query string, we can still build a reasonable page for them.

Back in template.php, underneath the setcookie script, add:

<?php if ($ "") {

} if ($page == "") {


} ?>

The syntax should look familiar to you now. This will set default values for our two variables if they do not already have values. So, a person skipping the redirect document and asking for will effectively be given

And there you have it: separating style, content, and structure. We’ve created template.php for the structure, and into that master document we’ve brought our separate style sheets and content files. We used PHP variables and require_once to insert the appropriate content and style, and did it in a way that
takes advantage of the latest style sheet-switching properties of current browsers, while also giving this ability to older browsers. Finally, using PHP cookies and a redirect, we made the site remember the user’s preferred style sheet.

You can see a modified version of these scripts at work at, and can download source files for today’s tutorial here.

Additional tutorials on php#section10

  1. ALA: How to Succeed With URLs
  2. PHP cookies
  3. PHP loops
  4. PHP arrays

More about French Communists#section11

  1. Babeuf’s
  2. The
    French Revolution and the Socialist Tradition
  3. Picasso:
    The Communist Years

Editor’s Note#section12

Obviously, there’s more to PHP than an introductory tutorial such as this article could possibly cover. Discussion in the forum provides insight into some of the additional issues (including security concerns) that come into play in any full-blown, PHP-driven Content Management System. Look for more on PHP and other server-side technologies in upcoming issues of A List Apart.

About the Author

Christopher Robbins

Christopher Robbins lives in Fiji, where he is helping set up an interactive and multimedia department at The University of South Pacific Media Centre. He rants like a French Communist at and keeps his capitalistic side tucked away at

72 Reader Comments

  1. What if someone enters in template.php?page=template ?

    Is there a way of stopping this?

  2. (In response to the template question above: you could say “if page=template, then [do something] … else, load everything normally”)

    Speaking of PHP management systems, I was frustrated by a lack of simple options, so I wrote my own 5k system called Rodin: . It’s open sourced, free, and is kept as simple as possible. A good template for beginners.

  3. Yes. You could do it in a few different ways. The easiest way would probably just be to check the value before you redirect. If it is “template”, then you can reassign the value.

    It should also be noted that in later versions of php (maybe 4.1+ ?), accessing querystring (URL) variables directly is no longer the correct way to do it and does not work by default. You have to access querystring variables through the $_GET array. In older versions, it’s recommended to use $HTTP_GET_VARS.

    James Craig

  4. A few notes to all you soon-to-be PHP converts out there…

    1) a header() call must be made *before* any HTML in the document

    2) a good shortcut for writing the value of a variable in (x)html is

    3) you can forgo the echo commands if you wish and section out your conditionals as such:

    4) you will no doubt get an error trying to write the xml declaration at the top as it is encapsulated in like php so the php engine will try to read it. you can circumvent this by having the php write out the xml declaration in an echo statement. just be sure to escape () your quotes (“).
    “; ?>

  5. Couple things:

    You should always be extremely careful when using include() or require() and user input. Never trust the user. In this case, possible bad side effects are minimized by adding the .html in the require call, but there is still the possibility mentioned above of including the template page. Probably the simplest solution is to make an array of acceptable pages and then verify that the page passed by the user is in that array…

    I also added a little error handling – if a bad page gets thrown to the script, it will include “error.html” which essentially acts as a custom 404 page. From there you can suggest other pages or just tell the visitor that they hit a bad page. Enjoy.

  6. Here are some more details on the security risks that have been mentioned above.

    This method of php programming is insecure with most default installations of php. It has been widly documented that you cannot trust external input. For example, on php 4.1.2 and older the following will load any file on your system that the web server has read access to (including /etc/passwd):
    (note, this requires that magic_quotes be turned on which is the default)

    You can also read any .html file on the system that the web server has access to. Let’s say this script was used on an intranet:

    Also, depending on how php is configured, an attacker can even load their own script and have it execute on your server as if it were a part of your application.
    would look like:
    in your code. By default this is turned on in most php installations.

    A solution (there are many others but this one is simple):
    Employ the deny all principle. Use a hash to lookup valid pages that can be loaded dynically. For example:
    $pages[‘index’] = ‘index.html’;
    $pages[‘products’] = ‘prodcuts.html’;
    // …
    // you’re even better off to validate the page lookup first and log any failures to a security log to help catch any attackers.

    Here are some references on secure php programming. There are many more but these should serve as a good introduction.

    Feel free to contact me if you have any questions, suggestions or concerns.


  7. As mentioned above, this style of coding can have very drastic security implications, and I wouldn’t recommend it.

    I use a variation of this system on my site. Here are a couple of tricks and tips I’ve picked up along the way:

    Proper use of quotes can really clean up your code, and potentially even make it faster. Double quotes “” tell PHP that there is something it needs to evaluate inside that string, so it’s great for something like
    echo “It is $time”;
    If you were going to echo out a string with no variables, do it using single quotes, like
    echo ‘XHTML and CSS rock my boat’;

    Escaping double quotes in a string can be a real mess, and I find it inconvinient, however there is an incredibly easy fix. Use single quotes for attributes inside your (X)HTML, which is fully compliant and don’t need to be escaped, like so:
    echo “$text“;
    There, nice and clean. Ahhhhh.

    When you’re coding one tip that could potentially save you a lot of time is to put the constant on the left of conditional statements. For example:

    Okay note all the changes there, first strings with no variables have single quotes around them. Next we have constants on the left. Why? Two equal signs mean it’s a logical statement, and PHP checks if they equal each other and return true or false, whereas one equal sign assigns value. So if you had this in your script as a typo:
    if ($secret = ‘yes’) {
    echo $secretstuff;
    It would get to the if statement and say “Is secret equal to ‘yes’? Sure! Let’s go!” This can be confusing when debugging, and hard to spot. If it saves you 10 minutes somewhere down the line, and doesn’t cost any time to do when you write the code, why not?

    I have had no end of trouble with PHP’s built in set-cookie function, espescially with it working right on older browser and redirecting people after the cookie had been set. My goal was to have a link people could click that would change the stylesheet (all server-side) and take them back to wherever they were (see for example). Here’s the code I ended up with, which would be ideal for a PHP CMS system like in the article:
    $cookielife = 365*24*3600; // set for one year
    $date = gmstrftime(“%A, %d-%b-%Y %H:%M:%S”,(mktime()+$cookielife) );
    header(“Set-Cookie: theme=$theme; path=/;; expires=”.gmstrftime(“%A, %d-%b-%Y %H:%M:%S GMT”,time()+10960000)); // old school way of setting cookies. Note the dot in front of the URL, this tells it to work for any subdomains as well
    header(‘Location: ‘.$_SERVER[‘HTTP_REFERER’]); // uses new $_ variable

    Finally just one minor note, instead of

    Why not have the container DIV tags inside the menu.php file? I find this more convinent, espescially for putting elements of your templete in other pages. Also note it’s generally a better practice to use id instead of class for unique elements.

    The simplest system I’ve ever used for templetes is also the one I keep coming back to because it works so well. A sample page would look like this:

    Everything I want on the page goes here, content, HTML, whatever.

    The header has the DOCTYPE, head stuff, echos out the title, runs a breadcrumb script I wrote (, and

    to start my content. The footer includes the menu, closes all the tags, and puts anything I want at the bottom of the pages. Another benefit that people have enjoyed when I show this to them is that it works well with Dreamweaver MX. I gave DW up a while ago, but I’ve seen the results and it works just like a DW generated templete might. If any of this has been unclear or you have any questions email me or visit my site. Enjoy!
  8. Back again. If you work a lot with XML it might be easier for you to turn off short_open_tag in your PHP configuration (php.ini) file. The downside is you will no longer be able to use method. An easier solution is to echo out the XML declaration like Aaron pointed out above, however the way he suggested to do it doesn’t work, at least on my system. You have to seperate the ?> part of the declaration, like so: ‘; ?> All we did here was concatenate (join) two strings, and there you have it. Go forth and create valid documents and XML! Of course using the

  9. Thanks for all the security input.

    I received a few more important security tips in the email:

    I saw your “A list apart” article about PHP content management linked from
    web reference. I just wanted to point out that you should do some checking
    on your page variables.

    At the very least, you might want to strip out slashes:

    $page = str_replace(‘/’,”,$page);

    That’ll keep people from looking around outside of your directory.

    [a few lines removed]

    I’d also recommend turning the warnings off for the site by adding something
    like this at the top of the script:

    Hope it helps.


    Paul Burney

  10. Hi…

    Not a bad article, but it would’ve been nice if the “echo” system was explained and what the different files would have looked like such as the menu…it took a while to figure it out – but i kind of got it.

    After messing with the way php works, i got it to work somewhat. After modifying things to work for what i want, i constantly get an error in line 15/16/17 or 18 and for the life of me can’t figure out what the issue is. The “includes” are all there calling the correct files but there are still glitches.

    But i got it to work enough that i’m hooked… so thanks.

  11. i had been pondering taking my .asp site and changing it to a .php site instead. all my dippy questions have now been answered and i think my weekend is also now taken care of.

    many thx

  12. The quotes in the following code:

    @import “$style.css”;>

    “; ?>

    may not be replaced with “ and ”. Quotes within HTML tags or PHP code must be regular quotes; only quotes that are part of copy should be written as “ and ”

  13. I am interested in learning PHP, but my website’s current host does not offer PHP support.

    Aside from changing host servers, can anyone tell me where I might be able to try my hand at authoring PHP pages for free in a live environment?

  14. Ron C: You could try installing Apache/PHP on your own computer (or PHP with another web server, but Apache is what I recommend). There are instructions on the web for doing this and a basic installation isn’t that difficult to achieve. The alternative would be to find a free web host that supports PHP. They do exist. I know from past experience that offers its members web hosting with PHP capabilities for the purpose of learning & practising the web development, along with a wealth of articles about web dev.

  15. Christopher mentions the use of a cookie to store user preferences, and accessing it directly through var $cookieName. However, in the most recent builds of PHP, these values are no longer directly accessible because of the security risk of an attacker setting variables directly by passing them in the request.

    So, on 4.2 or later builds of PHP, you’ll want to use the $_COOKIE[], $_GET[], and $_POST[] arrays to get styleCookie and page. And you’ll want to untaint any values you pull from the arrays.

    Following up on skye’s method for preventing an attacker from including an off-server page, I’d suggest creating an php object which generates the array of legal pages (via a directory traversal) or reads a site map file with the set of allowed pages. Of course, you pay a penalty in performance since the map has to be loaded and parsed with every invocation. — PHP really needs the notion of an Application-level object.

    — whump

  16. I’m wondering if anyone else had trouble getting the browser to recognize the alternate stylesheets? I’m using Moz 1.1a and it doesn’t see them.

  17. I spent a few minutes thinking about on-the-fly include path validation and came up with:

    Looking for $path.


    if ($path == $_SERVER[‘PATH_TRANSLATED’])
    print “

    Silly end user, you cannot load yourself.

    elseif (
    elseif (file_exists ($path))
    include_once ($path);
    print “

    Could not find $path.


    Which is intended to prevent any files off the server’s document path from being served.

    When I try the obvious attack:

    http://localhost/includeTest.php?file=..%2F..%2F..%2Fetc%2Fpasswd, the response is:

    Looking for /Library/WebServer/Documents/etc/password.

    Could not find /Library/WebServer/Documents/etc/password.

  18. I spent a few minutes thinking about on-the-fly include path validation and came up with:

    Looking for $path.


    if ($path == $_SERVER[‘PATH_TRANSLATED’])
    print “

    Silly end user, you cannot load yourself.

    elseif (
    elseif (file_exists ($path))
    include_once ($path);
    print “

    Could not find $path.


    Which is intended to prevent any files off the server’s document path from being served.

    When I try the obvious attack:

    http://localhost/includeTest.php?file=..%2F..%2F..%2Fetc%2Fpasswd, the response is:

    Looking for /Library/WebServer/Documents/etc/password.

    Could not find /Library/WebServer/Documents/etc/password.

  19. Ironically, the very idea of php (inlined code within a document) goes against the whole point of this article (separation of content and structure). Just thought I’d mention it 😉

  20. That’s why you do a lot of things which look like, but aren’t quite MVC in PHP. 🙂

    There are scripts such as Rael Dornfest’s Bloxsom which handle the the problem in the manner Joseph Ryan describes. Can you recommend other lightweight tools?

  21. I’m wondering if perhaps the author of the article could update the article and source files so as to reduce the security risk. I’m itching to try this out, but I don’t want to create a security risk, and I don’t know enough about PHP (read: nothing) to work the various fixes listed here in myself.

  22. Ditto to the post by Jan Van Tol. I too was eager to try this and even understood it all up until I came to the forum and read the discussions about the security issues.

    I’m still in the beginning stages of switching all my sites over to xhtml and making them adher to web standards. I know very little php. I did enjoy the article and understood it for the most part. But after reading the discussions, I guess my dream of being able to do this easily really means taking hours, days, and weeks to dig deeper into php. Ugh.

  23. Hi everyone,

    I have implemented the strategy discussed in this article. Right now I can access pages using Right now I’m also trying to add functionality discussed in which would allow me to link to pages simply by URL cloaking if you wish. Unfortunatelly that article doesn’t allow to post comments, so I’m seeking for help in here. 🙂

    The article above does give you a generic example of how to achieve cloaking effect, but when I adopt it to my case it doesn’t seem to work. This is what I use:

    RewriteEngine On
    RewriteRule ^([0-9]+) index.php?page=$1

    I’m concerned about ([0-9]+) part. It doesn’t look right. Will it work for any strings or only numerical ones?

    Please advise,

  24. Alex,

    You’re right, the ([0-9]+) part is only for numerical strings… It says to look for one or more numbers, and remember their value as $1. So what you need is something like:

    RewriteRule ^(.+) index.php?page=$1

    However, that will probably suck up all the other pages on your site and rewrite their URLs. I see two probable options — instead of taking anything after the domain name and adding that onto index.php?page= (like my first suggestion), make sure it doesn’t have a slash or a period in it:

    RewriteRule ^([^/.]+) index.php?page=$1

    This will make sure URLs like still work out if you need them to. Otherwise, add a prefix ‘directory’, like

    RewriteRule ^content/(.+) index.php?page=$1

    I think that’s all I’ve got. Anybody else?

  25. Ron C, here are some complete installations of php/apache/mysql which (are supposed to) work right out of the box – these are great for testing your php without having to find a host, or uploading updates if you do have a host. The only one of these I have used is phptriad, which works perfectly on the 3 machines I installed it on.

    PHPTriad –
    FoxServ –
    PHPDev –

  26. What a great article! I enjoyed monkeying (is that a word?) with the PHP code, and think your writing style is right on! Bravo!

  27. In response to Ron C…

    It is simple to test out PHP on Windows by using PHPTriad. It includes Apache, PHP, and mySQL. The install is very painless and the app is good for testing things out. Note this isn’t a long term solution, but it makes it very easy to check out PHP and see whether it’s worth investing more time in or not. The flexibility that the language offers in database interaction has been the true reward for me in converting applications to PHP.

    Download and info available at

  28. how do I declare the different pages? do I save ‘babeuf.html’ or ‘babeuf.php’? I dont understand where or how the actual content comes in to play?

  29. I’ve been using PHP templates for a couple of years now and wouldn’t have them any other way. The arrangement I use is a little different from the ones I’ve seen here so far though; as the one major downside I see of the template models suggested is that they require all your page content to be landed smack in the middle of an XHTML ‘wrapper’. There are often times when you want different pieces of content (page title, sidebar, page navigation, main article etc.) to go in different places in the template code; you can achieve this with multiple includes (eg the menu.php in the original article) but when you start getting down to 4 or 5 unique pieces of content for each individual page it just gets silly to break them into separate files.

    The model I use is as follows:

    – The file containing the actual page content is a PHP file (eg foobar.php) that encloses all its content in a PHP function called write_content().
    – foobar.php require()s a file called template.php.
    – template.php contains all the XHTML template code, and it calls write_content() where the content is meant to be placed within the template. In other words, puts it all together and outputs it to the browser.
    – Instead of requesting “template.php?page=foobar”, the user requests “foobar.php”.

    Why go to this trouble?
    – It limits the pages you can feed the template to the pages that actually exist. No verification needed.
    – It makes the urls cleaner and more intuitive, like a static site.
    – The content doesn’t have to all be put in the same place in the XHTML page code; it can have template code around and between it. For instance, foobar.php could have separate functions for sidebar content, navigation or ads, and a couple of variables that specify the page title and control the way the menu is highlighted to reflect the current page/section, etc. Template.php picks all of these up and slots them into the right places in the XHTML.

    The downside?
    – All your content has to be stored in php files, even if it’s all just plain HTML. You could parse an HTML page into separate chunks, but it’s not really worth the effort.
    – It causes headaches with using global variables within the page content, since it’s enclosed in a function and PHP (oh so kindly) requires you to specifically register global variables that you want to use within a function.

    This may seem like quite a few hoops to jump through and for many site applications it’s unnecessary; but I enjoy the flexibility it provides in allowing different areas of content to be placed individually within the template. I’d be interested to hear from anyone who has a more streamlined way of doing this.

  30. I have the following PHP problem:
    Up until now I’ve used the system of (pardon my syntax)


    include (header)



    I discovered that it would seem easier to deal with more advanced php scripts, and avoid some logical cath 22 situations using the variant described in the article, i.e.:




    I have decided to switch, but have run into problems…

    MY QUESTION is this: How do I read the variables from the content file prior to including it? Is it possible without resorting to meta tags inside the document or tricky php scan scripts (which as a novice I cannot do)?

    I might be wrong, but it seems I really need these variables BEFORE I include the file, since they have to be put into the XHTML document head.


  31. Uh…

    I was on p.1 when I posted my above question, unaware of Alun David Bestor’s posting dealing with this very issue here on p.2. Seems it would pretty much solve my problem. However, I can’t find a PHP function called write_content in the manual.

    Could you help me out?


  32. Re: uh.. 🙂

    write_content is just the name ADB has given to his php function which writes all the…um…..content to the page 🙂

    function write_content()
    echo “Hello, this is the content”;

    so he would have that at the start of his file, then he includes the page template:


    now, template.php could contain this:

    My Page

    …so, when he includes the template.php file, it will call the function write_content() which will output his content to the appropriate section of the page – so the user would get served this code when they go to foobar.php:

    My Page

    Hello, this is the content

    and the foobar.php sourcecode would look like this:

    give it a go yourself if you still can’t get your head round it.

  33. So when I place my

    prior to my

    my style changing links partially break. The style changes properly, but the $page variable no longer contains a value (ie a page name) in these links. Other non-style-changing links still work properly.

    Anyone else have this problem? I’m new to php, so maybe I’m doing something dumb? Both IE 5.2 and Mozilla do this.

  34. So when I place my

    prior to my

    my style changing links partially break. The style changes properly, but the $page variable no longer contains a value (ie a page name) in these links. Other non-style-changing links still work properly.

    Anyone else have this problem? I’m new to php, so maybe I’m doing something dumb? Both IE 5.2 and Mozilla do this.

  35. Any regular visitors who have used the Smarty Template System before? I’ve downloaded it but am clueless on how to actually use it. As with every programming-related documentations, Smarty’s was talking to me in ‘Greek’.

    And by the way, I enjoyed reading the article. Helped me out with some of the work which I am currently working on.

  36. As a PHP newbie trying to figure out the simplest way to include switchable content inside of a main template, I was ecstatic to see the “Switching content with PHP variables” part of this article. However, when I popped in the code (changing file names, etc. as necessary), I found that not only could I not display any of the content I wanted, but part of my layout was altered.

    I inserted the code inside of a table cell, as I just want the content to appear in this part of the template. Is this the problem? If the “include_once” doesn’t work in table cells, is there a similarly simple way to achieve the same results? Can anybody help me out here?

    By the way, my ISP does support PHP4.

    Thanks for any help anybody can give me.


  37. Hi Bill, I came across this very useful article to use PHP on my site I recently finished…being a bit of a newbie I used this to create a template (main.php) which used a header, footer, content left and content right all as include files then the main content in the middle of the page loaded using a variable ( $page ) in the way described ie


    the site is or if you want I can email you the main.php template and you can pick that one apart?

    Ive used include not require or include_once and all of them were inserted into tables and these have worked fine, not sure how much difference include and include_once would make.

    also, I had a problem with the layout changing and the only tips I can give is make sure that you are using a layout cell to insert the php* and that it is as wide as the page content you are loading (i decided to stick to a maximum width for all pages to make it simple for me)

    *In dreamweaver what I do is draw the layout cell then click inside it as if I was about to type or whatever then goto code view and insert the PHP at that point (also delete  ) and then it would look a bit like this:

    Hope that helps in some way as this forum was very useful for me!


  38. I can’t get the variables to load. I did everything as the article said.

    When I go to index.php, it redirects to template.php correctly, but I get a blank page. The source code is as follows on the template.php:

    Template.php — My first attempt at creating a dynamic website – September 27, 2002

    The URL is showing correctly:

    BUT I’m not getting any of body.html or menu.php files.


  39. There’s an even easier way to get around the security concerns expressed above. Put the html pages you want to include in the template into a subdirectory (i.e. /pages/). You can put Apache security on that subdirectory if you want, php will include the page without requiring a password even if there is Apache security on it. Then make a slight change to the require statement to say @require_once ($DOCUMENT_ROOT.”/pages/$page”). $DOCUMENT_ROOT is a php variable that shows the local path on your server (it looks like ‘/u/web/username’). The period between $DOCUMENT_ROOT and “/pages/$page” concantonates them so that the server will see something like “/u/web/username/pages/yourpage.html” By putting this in front of $page it will make invalid pages nonsensical and they won’t print. For instance, if you put an external page into the variable $page, the server would see ‘/u/web/username/pages/’ which wouldn’t produce anything since it’s a file that doesn’t exist. That also would prevent access to files on your local machine that you don’t want seen, so long as they do not reside in the directory you are using for this purpose.

  40. Thanks to insin for that rather more lucid explanation of what I meant in my previous post (“Another Template Model”) 🙂

    My question still stands, however: is there an easier way to implement the system described without using functions, since functions cause so many headaches with globals? Can large pieces of separate content effectively be generated and stored in simple variables, instead?

  41. I’m a beginner .. but to avoid infinite loop I do that :


    this way if you do ‘template.php?page=template’ you’ll get bla_template.php.

  42. I’m new to PHP, and a little confused about something… I used a setup similar to that described by Dave Hendler (on the first page), and it worked fine on my system (where I had installed Apache and PHP 4.2.3). Once uploaded, however, it no longer functions. My server says they support PHP 4, no version specified beyond that. Is there a reason the script I’m using won’t work on lower versions?

  43. Heya all, this code everyone has been displaying is a great help.. but im stuck on something.. Ive written some code so i can do the

    but i was looking at doing in one of those acceptable page arrays.. but i dont want to sit there and add every new page into that array.. is there a statement after the

    that i can add to basically say.. if $page.html does not exist.. go to error.html (without having the array remember)

    im new to PHP and would love the help .. Thanks!!!

  44. PHP beginner with little PHP experience. I am interested in setting up a site using includes (a template structure) and don’t quite know where to begin… I have the layout complete such as a header with nave which will remain the same on all pages, a left menu which will change per section, center content area which will change per page, and a right column which will also change according to section. I have tried regular but when I try to organize ny files into directories broken links are returned.

    Can anyone offer information on or a good resource for setting up templates and includes? Maybe I should start with something a little more simple?


  45. Several months ago, Ron asked: “Aside from changing host servers, can anyone tell me where I might be able to try my hand at authoring PHP pages for free in a live environment?”

    One answer is – you can try out lots of other stuff here too, like mySQL, Coldfusion, ASP etc. Absolute goldmine.


  46. You can check to see if a file exists and go on from there…

    Say $page contains the value which you got from the GET part of the URL. At the top of your page, you could have something like this:

  47. Hi guys

    Thanks for the great article intro to a php cms Chris 😉
    However, I am getting an error message like so when I put the code on my server:

    Warning: Failed opening ‘.html’ for inclusion (include_path=’.;c:php4pear’) in c:htdocsoneafrikan.comtesttemplate.php on line 16

    can anyone help??
    Does this have to do with passing variables in the url, and the method, and using a newer version of php??
    If so, how would one use $_GET to pull out the content using the $template variable??

    Thanks 😉

  48. sorry guys, i feel like a complete dumbass – found the solution to my problem through something similiar on sitepointforums…


    Cool… now i can add all the bells and whistles from the discussion!! 😉


  49. Hi guys

    Another query:
    I’m using the following method to get the page content using the variable passed to the template page:

    To do this, the url looks like so:
    … template.php?page=home.html&style=default

    The security concerns using this method have been discussed already, but what I want to know is if I can use the above $_GET method in some way so that I dont have to use the filename in the url…. Something like so:

    with a URl like:
    … template.php?page=home&style=default…

    On my server setup (php 4.2.3) this doesn’t work… but I’m wondering if i’m perhaps missing something, or if there is a way to do it I don’t know, or if there’s a different way to achieve the same thing.

    Thanks for the help!


  50. hi guys, me again with a answer to my post above – thought someone who is as new to PHP as I am may find it helpful….

    here is my template page:

    <?php echo $_GET['page']; ?>

    “; ?>
    “; ?>


    Hope that helps 😉


  51. I made my site for a group of people with massive differentiation in monitor size, and need to make style sheet switchers to help them out. So I’ve taken that stuff from this tutorial and left the dynamic content alone.. though am keeping in mind for the future!

    My problem is that my site has many pages, and is several layers deep. I’m not having a problem with the switching in the top level of my site, but further down I am, and I think it’s something to do with PHP not liking the ../../../ references back up to my style sheets at the top level. But I may be wrong.

    Is anyone able to help me with this? I’ve got the following code at the top of my document:

  52. I added the ../../../ to the stylecookie variable, but still no dice.

    I’m not very experienced with PHP and seem to miss a lot of things… what have I missed here?

    I’m also interested to hear the answer to Lars’ question (above) in case this doesn’t work out and I need to pass the variables along with the URL in every case.

  53. I’m working on a site (not published yet) using urls like
    So what I do is simply use ‘switch’ to include the proper page, and if anything ‘unknown’ is added to the url, or ‘goto’ is not set (ie: ‘’) it will simply display the default page which also happens to be the homepage.

    Something like this:

    case ‘blahblah’:
    include ‘blahblah.php’;

    case ‘lalala’:
    include ‘lalala.php’;

    include ‘home.php’;

    I cases where I don’t want to show a default page I will redirect with the header function:
    header(‘Location: http://www.mysite.php/errorpage.html‘);

    All the include files are stored in a seperate directory. This directory I prefer to put outside the webroot. But if that isn’t possible I put an index.php file in that directory whith the same header function.

    As far as I know all of this should go a long way in preventing any nasty people putting their noses where they shouldn’t be :).

    All comments most welcome.



  54. —->this is the variable that the menu buttons use to call the external php files, like content01.php etc. into the empty table in index.php.

    once i’ve set the variable in the index.php file, how do i get the home.php file to load into the table when people first arrive at the site.

  55. Php is a fairly easy language to learn and, as in this example, newbies can dabble around and get something working quickly BUT to produce good, secure code you have to have a more expert level of understanding. I wouldn’t want to put anyone off just make the point that you can’t jump straight into php from a web design background and expect to start producing good, dynamic websites in a couple of weeks. Six months of serious studying, maybe.

    Every time a website gets hacked it’s another easy story for a journalist in a thin week, and another blow for the internet as a safe place to do business..

  56. For over 2 days I’ve been trying…
    I keep getting in ‘view>sourse’,,, @import “null.css” /> ( in IE6)
    Also, in the dowload files for todays tutorial, the second half of the menu where your (supposed to) change styles, why is the no at the end?
    I get the page (additions) to change just fine, but can’t get the sytles to (even after trying with the added.). p.s. also… I know it’s (okay fine, “I’m”) stupid, but I spent the first few hours entering the url for the template.php, before figuring it out I’m supposed to enter the one for the index.php
    And was able to finally see the default.css work when I put in, if {$style=null} then {$style=default} any clues? I’m running out of hair to pull out 🙂

  57. This time I didnt see there was more than one page here (the “next” button) gareth (e) right on this page- ummm, thanks!!!!!
    I should drink more coffee maybe? LOL

  58. Just my 2 cents on filtering paths. Instead of str_replace(), you can call basename() on your path and it will return the filename only, devoid of directories.

    Of course, this will only work if all your articles are in the same directory.

  59. Hi, I’ve been desperately trying to figure this out for quite some time so any help is appreciaited! I’m not an expert at PHP so be warned!

    Basically I have these images and XML files in a directory. I want to create an index of the directory, but list only the XML files. I’d like the links in that list for each particular file to be the and <subtitle> from the respective XML file.</p> <p>What I’ve tried sometimes works, sometimes locks up, sometimes I get errors, sometimes nothing at all, etc…I just can’t figure it out and I need to get this working very soon. I’m using Sablotron on Linux.</p> <p>Here’s my code:</p> <p><?php function CheckExt($filename, $ext) { $passed = FALSE; $testExt = ".".$ext."$"; if (eregi($testExt, $filename)) { $passed = TRUE; } return $passed; } echo "<script language="JavaScript">n”; echo “function writestatus(say) { self.status=” [” + say + “]”; }n”; echo “function clearstatus() { self.status=””; }n”; echo “clearstatus();n”; echo “</script>n”;<br /> echo “</p> <style Type="text/css">n”; echo “Body { scrollbar-arrow-color:WHITE; scrollbar-track-color:white; scrollbar-shadow-color:#D6D6D6; scrollbar-face-color:#135184;n”; echo “scrollbar-highlight-color:#D6D6D6; scrollbar-darkshadow-color:#135184; scrollbar-3dlight-color:#135184; }n”; echo “A:link {color: #000000; text-decoration: none; font-weight: 300;}n”; echo “A:visited {color: #666699; text-decoration: none; font-weight: 300;}n”; echo “A:hover {color: blue; text-decoration: underline; font-weight: 300;}n”; echo “</style> <p>n”; </p> <p>//Define an array of common extensions.<br /> $exts = array(“xml”);</p> <p>echo “<b>Reviews in this folder:</b>“;<br /> $dir = opendir(“/home/ziphem/www/reviews/xml/”);<br /> $files = readdir($dir);<br /> $phpparser = “$files”;</p> <p>while (false !== ($files = readdir($dir))) {<br /> foreach ($exts as $value) {<br /> if (CheckExt($files, $value)) {</p> <p>echo “<a href=$phpparser" rel="nofollow"></a>n”;<br /> print “<a href='$files' rel="nofollow">“;<br /> // Create an XSLT processor<br /> $xsltproc = xslt_create(); </p> <p>// Perform the transformation<br /> $html = xslt_process($xsltproc, $files, ‘../xsl/movielist.xsl’); </p> <p>// Detect errors<br /> if (!$html) die(‘XSLT processing error: ‘.xslt_error($xsltproc)); </p> <p>// Destroy the XSLT processor<br /> xslt_free($xsltproc); </p> <p>// Output the resulting HTML </p> <p>echo $html;</p> <p>print “</a>“;<br /> $count++; //Keep track of the total number of files.<br /> break; //No need to keep looping if we’ve got a match.</p> <p>}<br /> }<br /> }<br /> echo $count.” Reviews Total.n”;<br /> echo “<a href="".$_SERVER["PHP_SELF"]."" rel="nofollow">Refresh</a>n”;<br /> //Be a good script and clean up after yourself…<br /> closedir($dir);</p> <p>?></p> <p>Thanks so much!!</subtitle>

  60. Sorry for my english:)
    I am new to php and i have start to make a template like ‘template.php?page=home that works great but in template.php there i have my meta tags and the title so if i have 5 diffirent pages i still have the same title is there a solution for? I realy have try evrything.

  61. How do i use test.php?page=
    to go to dir?

    ex: test.php?page=Athletics/Softball/

  62. Just a quick note. I finally pu this system into use and I discovered another security leak. For Example I have a directory with these files and directories:


    And you go to:

    Everything goes well, seeing as how folders and directory structure are still compatable with this system. BUT if you have a password protected directory(secretstuff) and someone types:

    They will immediately gain acess bypassing the security check…Does anyone know a way around this? I am actually using it to my advantage right now, but it is useful knowledge.


Got something to say?

We have turned off comments, but you can see what folks had to say before we did so.

More from ALA