Jump to content

Recommended Posts

I need to implement a site-wide header & footer include so that I can easily update content in one place.  Just recently I've moved my site from HTML to PHP and this is one of the first things I'd like to implement very soon. 

 

I work across two different hosts (i.e. testing server is www.testingserver.com/mysite and production www.prodserver.com/mysite, so I'm looking for a solution where I can easily switch sites without much maintenance.

 

Any suggestions? 

The way I implement a standard header/footer template type thing is like this...

 

header.php

<html>
<head>
<title><?php echo $pageTitle; ?></title>
</head>
<body>

<!-- some stuff and other code blah blah blah -->
<?php 
// content will get loaded here.

function footer(){ ?>
</body>
</html>
<?php }//end footer ?>

 

ContentPages.php

<?php
$pageTitle = 'About Us';// set the page title
include($_SERVER['DOCUMENT_ROOT'].'/header.php'); // include the header page
?>
My General HTML page content goes here.... blah blah blah
<?php
  footer(); // call the footer to close the page
?>

 

I basically cut the header page in 2. It can be a vertical cut for colums, or horizontal cut... Basically just determine where your content is going to load and what is a common area. By creating a function out of the bottom/right side of the page  I can then call the function and close out the page.

 

The drawback is you will pretty much need to use ob_start() at the very top of the header.php file and ob_end_flush() at the bottom.. as output has always started when you call include('...header.php').

 

But it works well for me and it is how I design pretty much every site I build.

 

By dropping out of PHP and into html and vice versa, I can design the page in a wysiwyg and see how it is going to look.

 

Lemme know if you have any questions.

 

Nate

Thanks for your reply Nate, I like your solution, however I have some questions.

 

1.  Will this line of code work for subdirectories?

<?php include($_SERVER['DOCUMENT_ROOT'].'/header.php');?>

 

For instance, if I include the header.php on a index.php saved at the root directory than this should work fine.  But will it work in a subdirectory (anotherfolder/index.php) ??  If not, how do you handle this?

 

2.  Regarding the footer, why use a function within header.php vs. having a file called footer.php and including it at the end of the page (similar to the header include) ?  I'm not saying it's wrong, but just trying to understand better since I'm a PHP newbie ...

 

3.  What exactly is the drawback with using ob_start() and ob_end_flush() at the bottom of header.php?  Any webserver issues here (I'll be testing in an Apache webserver and production is on IIS).

 

Thanks again for your help ....

 

T

Thanks for your reply Nate, I like your solution, however I have some questions.

 

1.  Will this line of code work for subdirectories?

<?php include($_SERVER['DOCUMENT_ROOT'].'/header.php');?>

 

For instance, if I include the header.php on a index.php saved at the root directory than this should work fine.  But will it work in a subdirectory (anotherfolder/index.php) ??  If not, how do you handle this?

 

2.  Regarding the footer, why use a function within header.php vs. having a file called footer.php and including it at the end of the page (similar to the header include) ?  I'm not saying it's wrong, but just trying to understand better since I'm a PHP newbie ...

 

3.  What exactly is the drawback with using ob_start() and ob_end_flush() at the bottom of header.php?  Any webserver issues here (I'll be testing in an Apache webserver and production is on IIS).

 

Thanks again for your help ....

 

T

 

1. No, I would actually make a constant out of it so you can define the subdirectory IE:

$folder = ""; // optional used if your script is not in the root of the site. remember the ending slash
define('DIR', $_SERVER['DOCUMENT_ROOT'] . "/" . $folder);
define('DIR_INC', DIR . "includes/"); // your includes directory
define('DIR_TEMP', DIR . "templates/"); // your templates directory

 

Etc etc. Then you would call it like:

<?php 
include_once('constants.php'); // so we have are variables
include(DIR_INC.'header.php');
?>

 

2. It is user preference. However you want to do it is the way you should do it.

 

3. You do not want to use that as it is a sign of poor programming. If you code everything right there is no need to add that extra step in there. Output code only when you are ready to output not just randomly.

Here is how I usually format my documents:

 

index.php

<?php include 'incl/includes.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Page</title>
</head>
<body>
<?php include 'incl/templates/header.php'; ?>
<!-- Some html and PHP -->
<?php include 'incl/templates/footer.php'; ?>
</body>
</html>

 

Now according to that template, I have an "includes.php" file, this includes things such as database connections, sessions, functions, arrays, etc. and I usually format it like this:

<?php
session_start();
include 'db.php';  // Contains the connection to the database
include 'functions.php';  // Contains all my custom functions
include 'arrays.php';  // Contains all my custom arrays
// etc...
?>

 

I won't show you how those files look, because they are very basic. But then I have my header and footer. I don't have examples of these because there are millions of customizations for each, but the header would contains things such as:

- logo

- navigation (usually horizontal under/next to logo)

- login and/or search fields

- etc.

 

Your footer would contain things such as:

- "FAQ" Link

- "T.O.S." Link

- "Contact Us" Link

- Copyrights (if any)

1.  Will this line of code work for subdirectories?

<?php include($_SERVER['DOCUMENT_ROOT'].'/header.php');?>

 

Yes, that is why I have it as $_SERVER['DOCUMENT_ROOT'], if you just call it as include('header'); then no it won't work in sub-dirs... but the way I call it works for as many subdirs as you can throw at it. In html, we can denote "start at root" with a leading forward slash, $_SERVER['DOCUMENT_ROOT'] is similar in PHP.

 

2.  Regarding the footer, why use a function within header.php vs. having a file called footer.php and including it at the end of the page (similar to the header include) ?  I'm not saying it's wrong, but just trying to understand better since I'm a PHP newbie ...

 

I do this because I design the page in a wysiwyg.. and I can design the page and not have to worry about broken code... or starting a div or table, and having it's finishing code in another page. I have just found it easiest this way. So more personal preference.

 

3.  What exactly is the drawback with using ob_start() and ob_end_flush() at the bottom of header.php?  Any webserver issues here (I'll be testing in an Apache webserver and production is on IIS).

 

Really, none that I have found... There may be some performance loss, but I can't tell...I just added this in there because if you try to do a header() redirect in a content page, you will get an error without ob_start.

 

 

3. You do not want to use that as it is a sign of poor programming. If you code everything right there is no need to add that extra step in there. Output code only when you are ready to output not just randomly.

 

With the way I have the "template" system setup, I have to use it because the output starts before the actual body content starts working, so any header redirects in the content pages will produce an error without it. I know it is not the best option, but I buffer the output and flush it when the entire page is done. No real big deal if you ask me... It simply hangs on to the page until it is completely done and ready to output.

 

 

@The Little Guy - I am not saying anything against yours, but I do mine this way so I only have 1 page that I have to mess with the html, head, title, body tags etc. I don't like having to deal with those tags in the rest of the pages. 1 page to hold my base code with css, js, includes and such.

 

I have a directory located at /lib/includes that contains all of my include files that contain array's, and other needed code. I also have a /lib/css & lib/js. I parse what is in the dir and add it to the page... When I want another file included, or js called or css added, then I just put the file in the dir and it is added.

 

Here is a sample of an actual page that I currently use... code has been cut from it to shorten it up for posting here.

<?php
ob_start();  
session_start();
////////////////////////////////////////////////////////
// include the db class  it lives below web root  // 
// and is used in about 5 different sites I have  //
///////////////////////////////////////////////////////
$serverRoot = null;
$array = explode('/', $_SERVER['DOCUMENT_ROOT']);
for($x=1; $x < (count($array) - 1 ) ; $x++){$serverRoot.= '/'.$array[$x];}
if(include($serverRoot.'/connect.php')){}else{echo 'could not include';};

$db = new cDatabase('timeclock');// instantiate the class so it is already done
//////////////////////////////////////////////////////
//           include our entire includes dir        //
//////////////////////////////////////////////////////
$includes = $_SERVER['DOCUMENT_ROOT'].'/lib/includes/';
if ($handle = opendir($includes))
{
  while(false !== ($file = readdir($handle)))
  {
if($file !='.' && $file !='..')
{
	include($includes.$file);

}
  }
closedir($handle);
}
else
{
echo 'could not open dir';
} 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<head>
<?php
////////////////////////////////////////////////
//           include our entire css dir          //
////////////////////////////////////////////////
$cssDir = $_SERVER['DOCUMENT_ROOT'].'/lib/css/';
if ($handle = opendir($cssDir))
{
  while(false !== ($file = readdir($handle)))
  {
if($file !='.' && $file !='..')
{
	echo '<link href="/lib/css/'.$file.'" rel="stylesheet" type="text/css" />';
}
  }
closedir($handle);
}
else
{
echo 'could not open dir';
}
////////////////////////////////////////////////
//      include the js directory             //
//////////////////////////////////////////////
$jsDir = $_SERVER['DOCUMENT_ROOT'].'/lib/js/';
if ($handle = opendir($jsDir))
{
  while(false !== ($file = readdir($handle)))
  {
if($file !='.' && $file !='..')
{
	echo '<script type="text/javascript" src="/lib/js/'.$file.'"></script>'."\n";
}
  }
closedir($handle);
}
?>
<title><?php echo $pageTitle; ?></title>
</head>
<body>
<!-- start header -->
<div id="header">
<div id="logo">
		<!-- truncated code.... navigation -->
</div>
<div id="welcomeCode">
<?php if(isset($_SESSION['user']['userId'])){?>
  <div id="welcome">Welcome, <?php echo $_SESSION['user']['username']; ?> <a href="/login.php?action=logout">[Logout]</a>
       </div>
  <?php 
              }
  ?>
</div>
</div>
<!-- end header -->
<!-- start page -->
<div id="page">
<!-- start content -->
<div id="content">

		<?php function footer(){ ?>


</div>
</div>
<div id="footer"></div>
</body>
</html>
<?php 
ob_end_flush();
};// end footer 
?>

 

This is the way I have found to be the easiest way to do things.... I like it and it works for me... it is a matter of personal preference...By doing this I can create new pages like this no matter how deep the sub-dirs are.

 

<?php
  $pageTitle = 'My Page';
  include($_SERVER['DOCUMENT_ROOT'].'/header.php');

   // content code here

  footer();
?>

 

It boils down to personal preference .. and this is my preference as it works for me and I have no issues with it. Hope it helps someone.

 

Nate

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.