PHP Basics – Structuring files

PHP has great ways of restructuring files to make it easier, quick, simpler and ultimately better at sending the right content to the end user. Here are a bunch of ways that you can achieve this in PHP


Even simple PHP based websites often require the same piece of code in several different places. the PHP Include command not only get the controller to retrieve a PHP template, it can also serve snippets of code so that you don’t have to keep writing it over and over again.

Include files can contain PHP, HTML or both.

We can include whats called a ‘template fragment’, such as the footer. This  HTML for the footer can be the include file:

   This is the footer &copy; Dan Johnson Whitstable.

Lets call the name of the file: This way, it’s easier to understand what the file is for just by looking at the file name.

we can then include this ‘include’ in any template page that requires a footer:

<!DOCTYPE html>
<html lang="en">
         <meta charset="utf-8">
         <title> Any ole page</title>
      <p>This page  uses a static include to display a standard footer</p>
      <?php include ''; ?>

Here is the controller that loads this template:

include 'any-ole-page.html.php';


 Establishing a database connection:

Put this code in its own file called

   $pdo = new PDO('mysql:host=localhost;
   dbname=mydatabase', 'username', 'mypassword');
   $pdo->exec('SET NAMES "utf8"');
catch (PDOException $e)
   $error = 'Oops, no database connection this time.';
   include 'error.html.php';

The controller would now show this:

include '';

 Note: When PHP comes across an include statement it puts the current script on hold whilst executing the include before continuing.


 Different types of include statements

  • include (Warning is displayed and the script continues*)
  • require (Error is displayed and the script stops*. Use with caution.)
  • include_once (Include statement will be ignored if already included.)
  • require_once (Include statement will be ignored if already included.)

*Warnings and errors are usually disabled in php.ini in production environments. Therefore a failed include will have no visible effect whereas a failed require will stop at the point of failure. When a failed require occurs before any content has been sent to the browser the unlucky viewer will see a lovely blank page!

Example: An index.php controller with an include for a query script that has an include for a database connection. Further down the controller another include with a different query script also asks for the same database connection include but it has already been loaded so it does not need to be parsed again.




Let php keep track of the DOCUMENT ROOT OF THE SERVER so that you don’t have to code absolute paths. List documents in any folder, on any server!

<?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/'; ?>

(The $_SERVER constant automatically records the document root as an array variable).



Reverse the changes made to user generated submitted values that PHP creates as part of it’s misguided ‘magic quotes’ feature by putting this code grab in its own include file:

if (get_magic_quotes_gpc())
   $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
   while (list($key, $val) = each($process))
      foreach ($val as $k => $v)
            if (is_array($v))
               $process[$key][stripslashes($k)] = $v;
               $process[] = &$process[$key][stripslashes($v)];
               $process[$key][stripslashes($k)] = stripslashes($v);

ans so here all you need to do is include it (using the document root constant):

include $_SERVER['DOCUMENT_ROOT'] . '/includes/';




In PHP, as with most scripting languages, it has built in functions that you can invoke at will. You would provide maybe one argument for it to use and maybe even receive a return value as a result. Listing PHP’s built in functions is beyond the scope of this article but did you know you can create your very own custom functions?

Here you define the function and keep it as an include file:

function totalplusvat($total, $vat)
{ return $total + $vat; }

The keyword ‘function’ declares a new function. area declares its name. (Names operate under the same rules as variables: case-sensitive, must start with a letter or underscore. May contain letters, numbers and underscores. there are no dollar signs though). Functions end with a set of parentheses which may or may not be empty. The parentheses enclose the list of arguments that the function accepts. When declaring a custom function you list variable names. Here, we list $total and $vat. When we call the function it expects the values of these two variables.

Lastly, inside the set of curly braces holds the code for the calculation, in this case a return statement. a return statement is used in PHP to immediately jump back into the main script. PHP does not read the rest of the script (if there is more) but returns to the main script. The return statement lets you specify a value for the function to return to the code that called it. In this case the value to be returned is the result of adding the values of the variables $total and $vat.

So here we see how we call this function by adding it as an include in our main script:

include_once '';
   $total = totalplusvat(200, 20);

include 'output.html.php';

“Don’t include custom functions more than once as you’ll get errors. Also define them at the top of the script so that you can see which includes are used by which script.”





A variable that exists in the main script will also be available and be changed in an include file. This is not always advisable as overwriting an important variable in an include is one of the main causes of errors. However, variables within a function are contained in the function. this is FUNCTION SCOPE. Variables created in the main script are not normally available to functions. These have GLOBAL SCOPE.

Therefore $total in the main script and $total in the function are separate.

In order to use the variable from the main script in the function you would import a global variable into the function scope:

function connection()
 global $pdo;

⋮ function statement

An alternative to importing a global variable is to use the $GLOBALS array:

   $result = $GLOBALS['PDO']-> etc

This special PHP array $GLOBALS is available across all scopes. it is a SUPERGLOBAL. Other superglobal PHP arrays include: $_SERVER, $_GET, $_POST, $COOKIE, $_FILES, $_ENV, $_REQUEST and $_SESSION.



The htmlspecialchars function is quite long and tedious to keep adding in a body of a PHP script. Normally every time you want to output user submitted text you need to use this function to prevent malicious code from entering your page.

For example, here we have used user submitted text in a list:

<?php echo htmlspecialchars($usertext['sometext'], ENT_QUOTES, 'UTF-8'); ?>

We can make this easier by putting this in a reusable function:

function html($text)
   return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

With this custom function we can call htmlspecialchars with a lot less typing:

<?php echo html($usertext['text']); ?>

But we can go one step further by taking the value generated by this function and outputting it using a second function:

function html($text)
   return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

function htmlout($text)
   echo htmlout($text);

So now all we need to do is to call these helpers in our main script:

<?php htmlout($usersubmitted['text']); ?>


So now, everytime you need some code more than once you can put it in it’s own little snippet as a template helper and call the function!