Making Your Web Page Elements More Dynamic with PHP Variables

One of my little PHP tricks I have become a big fan of is having a set of variables at the top of each file that I use to populate values later on in the file. For instance, I often bulk all of my <head> tag content into one file, and then have a “include_once(“headTag.php”);” to write it into each file in which it needs to be. If I do this though, I’m stuck with the same page title, description, etc. Or am I?

If I include a standard set of variables at the very top of each of my PHP files for my site, I can then utilize those variables in any file that is written into that file. So if I want a custom page title on each page, I can make a variable named $pageTitle_str, and set it equal to whatever I want to be the page title for that particular page.  Then, in the file that includes all of the <head> tag content, I would have a little PHP logic to echo that into the <title> tag.  And if I use conditional logic to echo it in, I can set the title to a default value in case the variable isn’t found.

Here’s how it’s done. In the example below, I have the PHP code for a fictitious page in my site that will be placed on the top of that file. I also have the <title> tag for the file that is written into this fictitious page, which includes the conditional logic to echo in the variable for page title.

File – fictitious.php
<?php
  $pageTitle_str = "Custom Page Title";
?>

File – headTag.php
<title><?php if ($pageTitle_str) { echo $pageTitle_str; } else { echo "Default Page Title"; } ?></title>

And that’s all there is to it. The <title> will be written out whether the variable exists or not. And if you include the variables on each page, you can do WAY more than just setting page title. You can set sections and subsections for use in styling in a top navigation file, or have custom descriptions or keywords for the <head> tag on each individual page. The possibilities are endless.

Until next time, happy coding!

There are no comments yet, add one below.

Leave a Comment