views:

54

answers:

1

I am trying to figure out a way to do this:

I want to have a core template file (structure.php):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<?php include_once(NAKIDROOT."includes/head.php"); ?>
</head>
<body>
<div id="all">
  <div id="page">
    <?php include_once("includes/header.php"); ?>
    <div id="main">
      <div id="left">
        <?php include_once("includes/left.php"); ?>
      </div>
      <div id="content">
      <?php include_once("includes/messages.php"); ?>
      <?php include_once("includes/page.php"); ?>
      </div>
      <?php include_once("includes/footer.php"); ?>
    </div>
  </div>
</div>
</body>
</html>

I would like the includes to have the ability to run header(Location) if needed so it seems like I would need to somehow have php read each of those include files.

Is there a way to render the include to check for headers and things first, and put its contents in a variable, so my structure file would instead be like this?:

<div id="page">
    <?php echo($header); ?>
    <div id="main">
      <div id="left">
        <?php echo($left); ?>
      </div>
      <div id="content">
      <?php echo($messages); ?>
      <?php echo($page); ?>
      </div>
      <?php echo($footer); ?>
    </div>
  </div>
+4  A: 

You cannot send headers after you've started on the HTTP response body (i.e. after you've output something, this includes things outside of <?php tags). A quick fix is to use output buffering using ob_start() and related functions. This is just a band-aid though; you should try to restructure your code so you don't have to rely on output buffering if possible.

To use ob_start(), simply call it at the top and call ob_end_flush() on the bottom of your script.

Daniel Egeberg
Beat me to it. Output buffering will allow your includes to send headers, since no content is actually sent until you explicitly send it, or the script terminates.
timdev
+1 for "This is just a band-aid though; you should try to restructure your code so you don't have to rely on output buffering if possible."
Byron Whitlock
How available/bad/slow is it to use output buffering? I was attempting this method for a CMS I am working on that could be distributed on multiple linux servers, which is why I did want to keep the include page files pretty simple
kilrizzy
It's not so much the speed, but rather the architecture of your application. Generally you shouldn't mix presentational logic with business logic. You would want to achieve a separation of concerns. One architectural design pattern that does this is called MVC (model-view-controller). This is a little too much to explain on SO, so try to look up those things. For now, output buffering can probably suffice until you're more experienced, but it's worth keeping in mind at least.
Daniel Egeberg
Awesome thanks!
kilrizzy