Home | All Questions | alt.html FAQ > PHP Hypertext Preprocessor (PHP)

How do I structure PHP scripts?

Using a template system like FastTemplate allows you to separate the php logic from the html layout, so making it a breeze to change the layout quickly and thoroughly.


Using the below method, you can make most of your sites very small. It also makes it possible to contain all the logic in one page for forms and validation using the switch statement & action commands. Using the $thisDoc variable defined in the template.php using PHP_SELF means that no matter what the document is named or however many times it is renames, you won't have to drudge through the code changing it because it's all self contained.

index.php

 <?php
 require($DOCUMENT_ROOT."/includes/template.php");
 echo PageHeader("Contact Info");
 ?>

 <b>body content goes here....</b>
 <p>This is where you put stuff to go onto your page...

 <?=PageFooter()?>

form.php

 <?php
  require($DOCUMENT_ROOT."/includes/template.php");
  require($DOCUMENT_ROOT."/includes/database.php");

  // --  connect to the db  --//
  $PageSize = 10;
  $dblink = db_connect("MyDatabase");

  switch ($Action) {
   Case 'FormVerified':
   // if a user sees this, then the form
   // has been verified.
    echo PageHeader('Form Verified!');
    echo "thank you, your form has been verified!";
    echo PageFooter();
    break;
   Case 'VerifyForm':
    if ('input_field' <> 'whateveriwhat') {
    // we have an error, let's deal with it.
     echo PageHeader('Oooops!');

     echo 'error: error reason';
     echo ShowForm();
     echo PageFooter();
    else {
     // if no errors, redirect to final stage of
     // form verification:
     redirect $thisDoc . "?Action=FormVerified";
    }
    break;
   default:
    /*
     default action, meaning that the $Action variable
     is not set (or is improperly set (someone trying
     to hack your form). This ensures that in most
     cases they get the form displayed to them...
    */
    echo PageHeader('Oooops!');

    echo ShowForm();
    echo PageFooter();
    break;
  }

  function ShowForm() {
   $thisForm =
    "<form action=\"$thisDoc\" method=\"post\">";
   // this next line sets the action variable
   // so that the page knows to 'verify' the form
   // when the user clicks ok
   $thisForm .=
    "<input type=hidden name=\"Action\"" .
    " value=\"VerifyForm\">";
   $thisForm .=
    "<input name=\"input_field\">";
   $thisForm .=
    "<input type=submit name=\"Submit Me!\">";
   $thisForm .=
    "</form>";
   return = $thisForm;
  }

template.php

 <?
  $thisSiteTitle = "My Site.com";
  $thisDoc = $PHP_SELF;
  $thisDate = getdate();

  function PageHeader($thisTitle="") {
  /*
   the title you pass to this function is appended
   to a string to maintain consistancy i.e. if your
   site title is "Joe's Radio Shack" and the parameter
   thisTitle is 'Buy Here', the resulting string in
   the window title bar would be:
   "Joe's Radio Shack :: Buy Here"

   Other things I've found useful to put as parameters
   in my dealings with other languages
   such as ASP and JSP, but have not done in PHP yet:
   passing:
   1) OnLoad parameters for javascript
   2) MetaTag information (if a page has a specific
      <meta> tag that the rest do not
   3) language information...
  */

  global $thisSiteTitle, $thisDoc, $thisCSS;
  if ($thisTitle != "") $thisTitle = " :: ".$thisTitle;

  # Page Headers
  header("Cache-Control: no-cache, must-revalidate");
  header("Pragma: no-cache");
  header("Expires: Mon, 26 jul 1997 05:00:00 GMT");

  # Start Document Header
  $thisHeader = "<!DOCTYPE HTML PUBLIC " .
   "\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n";
  $thisHeader .= "<head>\n";
  $thisHeader .= "\t<title>".
   $thisSiteTitle.$thisTitle."</title>\n\n";
  //.... <STYLE>, <SCRIPT>, <BODY>
  // tags & basic navication can go here ...

  return $thisHeader;
 }
 // END HEADER

 function PageFooter() {
  /*
   ok, so now here you can put your 'bottom'
   naviation links and your copyright/
   all rights reserved statements
  */
  $thisFooter .= "</body>\n";
  $thisFooter .= "</html>\n";
  return $thisFooter;
 }
 // END FOOTER
 ?>

Creating your own template parser

 function parse_template ($filename, $replacements='none')
 {
  global $template_dir;
  $file = @fopen($template_dir.$filename, "r")
  or die("Could not open template file $template_dir$filename");
  $contents = fread($file, filesize($template_dir.$filename));
  fclose($file);
  if (is_array($replacements))
  {
   while (list($code, $replace) = each ($replacements))
   {
    $contents = eregi_replace($code, $replace, $contents);
   }
  }
  return $contents;
 }

Recommended Resources

Discussion

Related Questions