Including Content With PHP

Wednesday, March 10, 2004 at 5:44 pm | Comments off

For all recent sites that I've made, I've used PHP to include the header and footer on each page. Doing this allows me to make a change to one file, and have the entire site respond. For the sake of clarity, a given (static) page on this site would have, until today (more on this later), looked something like this:

<?PHP
include $_SERVER['DOCUMENT_ROOT']."/header.php";
?>

<p>Content here</p>

<?PHP
include $_SERVER['DOCUMENT_ROOT']."/footer.php";
?>

So basically what I do is split each page where the content begins and ends, and throw it in separate files. This does, however, have on major drawback: each page's header information is the same. For me, the biggest issue with this was the fact that the title remained the same from page to page, when I would rather use a more descriptive title for each page. Why? Well because the title is the most important element on a page, of course. Good titles are very important to SEO.

So, today I decided to deal with this problem. Rather than simply include the headers and footers, I've chosen a new method. I now read the files into a variable, evaluate the string (because I use PHP code in both the header and footer), run a regexp on the title, and echo out my header.

Let's take a look.

<?PHP
# grab the files contents (PHP 4.3.0+ with this method)
$header_str = file_get_contents($_SERVER['DOCUMENT_ROOT'].»
"/header.php"); # get the contents of the header file
$header_str = "?>".$header_str."<?php "; # set up the »
$header_str.

/*We need to prepend the ?> and append the <?PHP because
eval() automatically adds tags to the beginning and end. 
If we do this, it will parse our PHP correctly. */

ob_start(); # turn on output buffering
eval($header_str); # evaluate the string as PHP code
$output = ob_get_contents(); # return the content of the »
output buffer to our $output string
ob_end_clean(); # discard the output buffer

# do some replacing
$output = preg_replace("/<title>(.*?)<\/title>/", "<title>»
Ryan Brill | About Ryan Brill</title>", $output); 

echo $output; # echo our header
?>

This will change from the default title seen on my index page, to a title more appropriate for page describing the designer. The comments should explain what's going on, to those who understand PHP. For those at a beginner level, you simply need to change the top line to point to your included file, and the line after the # do some replacing comment, to change your title.

Obviously, this can be used for many other things. The power is in knowing how to read the contents of a PHP page into a variable, while still parsing the PHP code on that page.

Comments

Ben Scofield
March 10th, 2004
6:59 PM | #

Wouldn't be it easier just to do something like this?

<?php
// About page
$title_to_show = "Ryan Brill | About Ryan Brill";
include $_SERVER['DOCUMENT_ROOT']."/header.php";
?>
[page stuff]

with

<?php
// header.php
[header stuff]
echo "<title>$title_to_show</title>";
[rest of header stuff]
?>

No reading files into variables, no parsing of regular expressions - just good ol' variable interpolation. Remember, when you include or require a file in PHP, it's as if that file is plopped directly into the host file prior to processing, so it's a simple matter to pass variables into an included file.

[note: this is not actually the method I use - I prefer to encapsulate the header and footer into functions in a larger config file, passing page titles and the like in as parameters. The method I describe here does work, though.]

Ryan
March 10th, 2004
7:40 PM | #

Yes, that would be another way, though as I said at the end of the entry, the point of this was to show how to read a PHP file into a string, perform changes on the string, and still have your PHP parsed as PHP. While there are other (perhaps easier) methods of doing what I just showed, it still is very useful, IMO.

Ben Scofield
March 10th, 2004
8:57 PM | #

Ack - sorry, then. I was focusing on the problem expressed at the beginning of the post. Perils of commenting without reading all the way down, I guess.... My apologies.

Ryan
March 10th, 2004
10:15 PM | #

No problem at all. I probably should have gone about writing this entry a bit differently, as your method would make more sense, in many cases. However, for what I needed to do, this was the perfect solution , as I wanted to use my standard header, without making any modifications to it.

Daniel
March 11th, 2004
2:48 PM | #

ryan, good job i enjoy reading your blob. fwiw, although i know this was not your intention and i am new to php in general, i found that this worked greatly on the last site i did for client:

class Page
{
var $title = 'ryan brill'; //default title

function displayhead($newtitle="")
{
if(!empty($newtitle))
{
$this->title = $newtitle;
}

//echo header stuff here
echo "<title>" . $this->title . "</title>";
//echo more header stuff
}

//write similiar function for footer ec..
}


Then on my pages just do this

$page = new Page();
$page->displayhead("ryan brill | info");

//content here

$page->displayfoot();

Colin Viebrock
March 17th, 2004
6:30 PM | #

Uh, couldn't you just do this:

<?
include 'layout.php';
commonHeader('Title of this page');
?>

<p>content</p>

<? commonFooter(); ?>


Your layout.php file would have functions commonHeader and commonFooter() -- that output the header and footer text for the page. Each function can take arguments to change the output, like specifying the <title> tag in the header.

This is how I designed www.php.net to work.

PHP's eval() is a really slow function (and a potential security risk). Regular expression replacements aren't terribly quick either, although the effect on a small website is probably unnoticeable.

Conor
April 6th, 2004
3:42 PM | #

an interesting method, i use the same thing the first person posted but for what you are trying to do this seems to be the way to go

malaga
March 27th, 2005
11:27 AM | #

Greetings from Malaga (Spain). Antonio :-)

gabe
July 26th, 2005
11:39 PM | #

Great code Ryan.

Interesting to note, though it may seem obvious to most, is that when you use

file_get_contents($path_to_file);

and the $path_to_file is a local directory path, the original php code is returned.
However if $path_to_file is a url the contents is the php output, like html.

If we used Ryan's Code to include content from a different website (http connection) we just have to remove the eval(); function and the added php tags around the header code to make eval() work. Then you can play with your content.

Ryan's Code comes in very handy when you are including content from php files that you cannot alter. (local files).

This occurs if you are writing an extension for an application that has other extensions that will be installed at a later date, or at differnet websites you dont have access to.

In these cases, the only information available to your script is the location of these extensions files.

With this you can still include the content from these files in your own script.

Comments are automatically closed after 45 days