Project “Ragtime”: variable page titles
Now that you know about variables in PHP, let's take our little project "Ragtime" one small step further and satisfy a little SEO (Search Engine Optimization) requirement.
The importance of titles
In the initial version of the Ragtime site (demo here) the header part of every page was in an include file with the idea that this part is the same across all pages. So the <title> was always "Ragtime". Well, search engines prefer that the title tag represents the content on a page, so for example the products page is better titled "Products". Since the titles varies, it could be stored in a variable.
The new header
The new header is the same as the old one, except for the title. Let's take a look at the HEAD section:
<head> <title>Ragtime > <?php echo $title; ?></title> <link rel="stylesheet" href="ragtime.css" type="text/css" /> </head>
In the title tag we'll print the contents of a $title variable. Where is this variable defined? In every page, as we'll see in a bit. Let's take a look at the welcome page.
The welcome page
The difference with the previous version is that now before including the header.inc, this page defines the $title variable. As you can see, it's perfectly fine to define a variable in one file and use it in another. All files included after a variable is defined will have access to its value. In this case it's important that the variable is defined before the header is included, otherwise it won't work.
<?php $title = 'Welcome to Ragtime!'; include 'header.inc.php'; ?> <h1><?php echo $title; ?></h1> <p>Select a link from our nice menu</p> <?php include 'footer.inc.php'; ?>
As you can see, the page also reuses the $title variable in the H1 tag, this way if you ever need to change the title, you only need to do it in one place.
Demo
The other pages are working the same way as the home page, they just define $title before they include the header.inc.php. You can download the code and play with it, you can also check out the new demo.