Server Side, Making Your Life Easier: Part 3 – PHP Headers and Footers with Defaults

As I mentioned in my previous post, there are some old deprecated things here, I’ll update later.

You now know how to create and display variables with PHP. Here is a review of everything I’ve used so far.

How to break in and out of PHP:

  1. <?php
  2. //PHP Code Goes Here
  3. ?>

How to set a variable:

  1. <?php
  2. $variable = "Variable Value";
  3. ?>

How to quickly display a variable:

  1. <?=$variable?>

Now we are going to use “if,” “else,” and “echo” to set default values for the title, and meta tags. There won’t be a step by step process for this one, I’m just gonna display the sample code for header.php. Everything else is done almost exactly the same as Part 2.

  1. <html>
  2. <head>
  3. <title><?php
  4. if ($title) {
  5. echo "$title";
  6. } else {
  7. echo "Site Title – Tagline";
  8. }
  9. ?></title>
  10. <meta name="description" content="<?php
  11. if ($description) {
  12. echo "$description";
  13. } else {
  14. echo "Default META Description";
  15. }
  16. ?>">
  17. <meta name="keywords" content="<?php
  18. if ($keywords) {
  19. echo "$keywords";
  20. } else {
  21. echo "Default META Keywords";
  22. }
  23. ?>">

Now, if you want to use the default values, just remove the line that sets the variable from the content page. You can also comment out the line to add it back in later. The following example will only pass on a unique title to the header.

  1. <?php
  2. $title = "Page Title Goes Here";
  3. //$description = "Page Description Goes Here ";
  4. //$keywords = "Page Keywords Go Here ";
  5. include(‘header.php’);
  6. ?>

Thats it, this will make your life easier. This should also give you a good start to using simple PHP. There are many more area’s of server side scripting you should explore. It will replace buggy, error prone client side scripting in many ways, such as; Browser Detects, Redirections, Cookies, Form Validation, and much more. If you are already familiar with JavaScript, PHP will be a breeze.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.