Creating a PHP header/footer

rjwctm21 picture rjwctm21 · Nov 8, 2011 · Viewed 139.3k times · Source

I'm designing a relatively simple site for a friend. I would like to impliment php so that he can change his header/footer without having to go back through every file. Problem is, I'm pretty much totally unfamiliar with how php works. Is there a simplistic way to do this? I've seen a few answers for how to make a php header but they all seem different and I haven't had much success. I'm not saying they don't work (I probably did it wrong) but the simpler in this case, the better.

Thanks!

Answer

William picture William · Nov 9, 2011

Besides just using include() or include_once() to include the header and footer, one thing I have found useful is being able to have a custom page title or custom head tags to be included for each page, yet still have the header in a partial include. I usually accomplish this as follows:

In the site pages:

<?php

$PageTitle="New Page Title";

function customPageHeader(){?>
  <!--Arbitrary HTML Tags-->
<?php }

include_once('header.php');

//body contents go here

include_once('footer.php');
?>

And, in the header.php file:

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title><?= isset($PageTitle) ? $PageTitle : "Default Title"?></title>
    <!-- Additional tags here -->
    <?php if (function_exists('customPageHeader')){
      customPageHeader();
    }?>
  </head>
  <body>

Maybe a bit beyond the scope of your original question, but it is useful to allow a bit more flexibility with the include.