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>
<div class="menu">
</div>

require_once()#section3

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>
<div class="menu">
<?php @ require_once ("menu.php"); ?>
</div>

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"); ?>
</div>

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" 
media="all">@import 
"$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" 
media="all">@import 
"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" 
type="text/css" 
href="print.css" title="Printable" />"; 
?>
<?php echo 
"<link rel="alternate style sheet" 
type="text/css" 
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:

<?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 FrenchCommunists.org, the user would
have to enter www.FrenchCommunists.org/template.php?page=babeuf&style=default.

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 www.FrenchCommunists.org.

PHP redirects#section8

A straightforward PHP redirect would look like this:

<?php Header ("Location: 
http://www.FrenchCommunists.org/template.php?page=home&style=default"); 
?>

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:

<?php
<if ($styleCookie == "") { < $
<}
<else { < $
<}<Header ("Location: 
http://www.FrenchCommunists.org/template.php?page=home&style;=$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:

$style="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: 
http://www.FrenchCommunists.org/template.php?
 page=home&style;=$style");

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 == "") {

$page="home";

} ?>

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 http://www.FrenchCommunists.org/template.php will effectively be given http://www.FrenchCommunists.org/template.php?page=home&style=default.

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 webactivism.org, 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
    Defense
  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 webactivism.org and keeps his capitalistic side tucked away at grographics.com.

72 Reader Comments

  1. 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:

  2. 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 😉
    Gareth

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

    try:

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

    Gareth

  4. 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!

    Gareth

  5. 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 😉

    Regards
    Gareth

  6. 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:

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

  8. I’m working on a site (not published yet) using urls like http://www.mysite.com/index.php?goto=blahbah
    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: ‘www.mysite.com’) it will simply display the default page which also happens to be the homepage.

    Something like this:

    switch($goto)
    {
    case ‘blahblah’:
    include ‘blahblah.php’;
    break;

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

    default:
    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.

    Greetings

    Rik

  9. —->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.

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

  11. 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 🙂

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

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

  14. 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=”Terriblemovies.com [” + say + “]”; }n”; echo “function clearstatus() { self.status=”Terriblemovies.com”; }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 = “http://www.terriblemovies.net/reviews/xml/standardbrowser.php$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>

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

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

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

  17. 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:

    index.php
    aboutus
    thisismusic
    secretstuff

    And you go to:

    http://www.domain.com/index.php?p=aboutus/index

    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:

    http://www.domain.com/index.php?p=secretstuff/index

    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.

    Jakks

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

I am a creative.

A List Apart founder and web design OG Zeldman ponders the moments of inspiration, the hours of plodding, and the ultimate mystery at the heart of a creative career.
Career