demosthenes.info

I’m Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with , and . To receive more information, including news, updates, and tips, you should follow me on Twitter or add me on Google+.

web developer guide

my books

Book cover of Pro CSS3 AnimationPro CSS3 Animation, Apress, 2013

my projects

A Sass color keyword system for designers. Replaces CSS defaults with improved hues and more memorable, relevant color names.

CSSslidy: an auto-generated #RWD image slider. 3.8K of JS, no JQuery. Drop in images, add a line of CSS. Done.

tipster.ioAutomatically provides local tipping customs and percentages for services anywhere.

Lao Che

“Self-Made” Pages With PHP, Part I

php / navigation

Estimated reading time: 5 minutes, 24 seconds

One of the common overreaching uses of includes that I mentioned previously is to replace the entire leading section of HTML code, including the <head> section, in a single include file. This of course, causes every page to have the same title and meta tag values, which is unacceptable. However, with a few PHP functions and features we will introduce here, including PHP_SELF, constants, str_replace(), ucwords(), and filemtime(), we will show how it is possible to have a single include file containing the entire <head> section that still allows for a unique title and meta tag values on each page.

First, a few assumptions and rules:

  • Aside from index.php, the filename of the pages of your website will always reflect their intended purpose, and when multiple words are used in the file name they are separated by hyphens. For example, popular-routes-to-india.php. (Hyphens are preferred by Google and other search engines over underscores in filenames).

  • The majority of the meta tags will be the same from page to page: for example, you will always be the creator of the page.

  • You will never require an embedded stylesheet: all style declarations will either be in a linked stylesheet or written inline.

With those assumptions in place, let’s take a look at the HTML code for the popular-routes-to-india.php page of the fictional website for Lao Che Air Freight:

<!doctype html>
<head>
<meta charset=UTF-8 >
<title>Lao Che Air Freight - Popular Routes To India</title>
<link rel="shortcut icon" href="lao-che.ico">
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="wrapper">
<h1><a href="index.php"><img src="assets/images/lao-che-logo.jpg" alt="Lao Che Air Freight" style="width: 100px; height: 50px;" /></a></h1>
<nav>
<a href="index.php">Home</a>
<a href="about.php">About Us</a>
<a href="popular-routes-to-india.php">Popular Routes To India</a>
<a href="prices.php">Prices</a>
</nav>
<main>
</main>
</html>

This page has nearly everything: a link to a stylesheet and favicon, a logo inside a <h1> element, a navigation bar, etc. As you can guess, the majority of the code, from the very first line to the opening <div> tag for the content section, will be exactly the same from one page to the next: the only details that would change would be the title content. Let’s do the previously unthinkable: take that entire section of code and make it a single include called pagestart.php.

Let’s say we placed the pagestart.php file in an includes folder inside the assets folder. So our popular-routes-to-india.php page becomes:

<?php include('assets/includes/pagestart.php'); ?>
</div>
</body>
</html>

The unique content for the page will be placed between the include and the closing </div>.

Turning back to the include itself, the most glaring issue is the fact that each page on which it is used will have the title Lao Che Air Freight – Popular Routes To India. Let’s improve on that. Change the <title> section of the include to:

<title>Lao Che Air Freight - <?php echo $_SERVER['PHP_SELF']; ?></title>

… and upload your files to the server, viewing them in the browser. Depending on your server setup and where you are saving your files, you will see something like this as the title:

Lao Che Air Freight - /site/popular-routes-to-india.php

(Note that $_SERVER['PHP_SELF']reflects the filename of the page, not the include).

There are a few things we want to do to improve the PHP statement within our <title>: obviously, we need just the filename of the page, without the directory structure of which it is a part:

<?php echo basename($_SERVER['PHP_SELF']); ?>

We also want to eliminate the .php extension on the end:

<?php echo basename($_SERVER['PHP_SELF'],”.php”); ?>

…and convert the hyphens used in the filename to spaces:

<?php echo str_replace("-"," ",(basename($_SERVER['PHP_SELF'],".php"))); ?>

Finally, we want to make the words used in the title capitalized. Ironically, we can’t use CSS to do so, as text-transform: capitalize only affects content within the <body>, not the <head>. So instead we must use the ucwords() PHP function:

<?php echo ucwords(str_replace
("-"," ",(basename($_SERVER['PHP_SELF'],".php")))); ?>

(Note the parentheses growing as we use each function).

We want to use this generated title at least once in the <title> itself. Any time we expect to use something more than once, we must consider how to do so with greater efficiency. In this case, we don’t need a variable, as the filename of the page is not going to change during the execution of our script; instead we’ll take the function that we developed and use it to define the value of a constant, at the very start of our page:

<?php define ("title", ucwords(str_replace ("-"," ",(basename($_SERVER['PHP_SELF'],".php"))))); ?>

Constants are defined only once; the name of a constant may be any single word that does not begin with a numeral or $. (It’s a common mistake to forget to start a variable name with the required $ sign; which often results in the server saying that it is an undefined constant).

Now we can use the title constant in both places in our code:

<title>Lao Che Air Freight - <?php echo title; ?></title>

The other meta tag we should change is date. This refers to the last date of creation for the document. (It is also possible to use DC.date and DC.revised as separate tags, recording when the document was originally created and when it was last revised). The date used must be in the format yyyy-mm-dd.

Rather than doing this by hand, let’s use PHP to inspect when the file was last modified. As a test, somewhere below the opening content <div> in our include file:

<p>The file was last modified on:
<?php echo (filemtime(basename($_SERVER['PHP_SELF']))); ?></p>

This gives us a result that is in Unix time format. For our date meta tag, we want to convert that to the correct format, using the date() function:

<meta name="DC.date" scheme="DCTERMS.W3CDTF"
content="<?php echo date ("Y-m-d", filemtime(basename($_SERVER['PHP_SELF']))); />

Summary

While the effort to complete the include file was considerable, the benefits are significant: to start a new page on the Lao Che website, all we need to write is:

<?php include('assets/includes/pagestart.php'); ?>

Everything – the page title, the link to the stylesheet, meta tags – is taken care of. All we need to remember is to provide a good filename for our page, with words separated by hyphens, and everything else is generated for us. This significantly speeds up the creation of new pages, allowing us to concentrate on content rather than code.

comments powered by Disqus

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.