<? Functional Includes?>

Functional Includes

 

Unified Site Architecture: When we put together our site files, we wish to retain as much flexibility as possible, while maintaining minimal locations for making site changes.  To accommodate this apparent contradiction, we use include files to house recurring HTML elements, CSS styles & code.  Previously we split our PHP design into structural include files (a header and footer). Now we're going to use this technique again, but now it will be to centralize functional code.

Centralized Configuration: When we started to work with the database, we placed all database credentials in a single file and included it.  Rather than providing configuration, error handling or database credentials on every page, it makes sense to create a single include file to provide all of these settings, and then reference that file once on each site page.  As we add functionality or encounter issues with PHP that require site-wide changes, we'll be rewarded for choosing to centralize our code in this way.

In our case, the name of this single include file is config_inc.php.   which will store all site-wide configuration information.  'config' is short for 'configuration' and we'll continue our convention of ending our include files with _inc.php to indicate the file is not a navigable page.  config_inc.php will itself include references to additional include files, that handle related process information.

Three Primary Include Files: We can include as many files as we wish because PHP sees all available code available as an unending continuum.  Humans however may wish to separate our code into 'modules' to aid in comprehension.  Also, there may be times to include pieces and parts of functionality in some pages, and not others.  For all these reasons we've split our functional includes into 3 files:

  • config_inc.php: stores all PHP configuration settings, site wide constants, file paths, error handling, and references to the next 2 files.
  • conn_inc.php: stores database credentials, MySQL permissions and connectivity functions
  • common_inc.php: stores various utility functions for string and page processing

config_inc.php will store references to the other 2 include files, so we'll only need to reference config_inc.php once at the top of all our site files. 

Paths As Constants: One of the include files, config_inc.php allows us a single place to store important site information designed to allow configuration changes.  This is the one file we'll need to include, because it will be aware of all other related include files and will store all pathing information as constants, for example THIS_PAGE, VIRTUAL_PATH ERROR_LOG. Placing pathing information in constants allows them to automatically be available in every function, and not be changed by code. 

Error Handling: There are also error handling functions built into config_inc.php.  An error handler is code that processes an error in a particular manner.  We’ll choose to display different data about page errors based upon current conditions.  In general, we want to see errors while we develop, but want to hide them while our users are using our pages. View the following versions of the same test page error_test.php, which is set to show all errors or display a generic error for users.

Inside config_inc.php, we'll override the default PHP error handler.  By doing this we can write our own code that will respond to errors.   We can handle all visible errors on the page, and present a ‘user friendly’ error reporting page that generates a unique ‘code’ to allow our customers to help us troubleshoot.  If we set a constant inside config_inc.php named SHOW_ALL_ERRORS to TRUE then all manner of page errors are visible, which is what we'll want while developing the site. When the constant SHOW_ALL_ERRORS is set to FALSE most non-fatal errors show up in a user friendly manner.   To test this, change these settings in config_inc.php and view a special 'flawed' page named error_test.php page to view how errors currently appear.

Tailing the Log File: If errors are currently ‘hidden’ but are still being logged, in UNIX we can setup a ‘tail’ to follow the changes to this file via the command line:

tail -f /home/classes/horsey01/log_sprockets/error_log

With a command line window open we can view errors as they occur in this way.

Note that there are several different error levels, and many are ‘fatal’, meaning they are not easily caught by code and will crash a page regardless of error handling (for example a simple parse error). However, once our code is tested it's unlikely these errors will remain.  For more details, see error handling in PHP.

Functions in common_inc.php: This file stores our ‘user created’ utility functions.  One of these functions is called dbOut(), which is designed to ‘clean’ the string of data as it leaves the database, and enters our page.  This function is called a wrapper, because it ‘wraps’ other functions that we can now change, as our site develops, or if we need special handling. Placing all the ‘cleaning’ code in a wrapper allows us to change this capability site wide.

On an insert SQL is tripped up by single quotes.  Internally dbOut() implements stripslashes(), which along with its opposite addslashes() render harmless single quotes, by escaping the quote by adding an extra 'slash'.  In SQL, single quotes are used to designate a string, but must be escaped (by adding a slash in front of the literal quote) to be entered into the database.

When we wish to enter data into the database, we use a matching wrapper function named dbIn(), which internally uses a PHP function named mysql_real_escape_string() to sanitize (clean hacker bits) from data to be entered in the database.  Since PHP is prone to improving its own functions, using a wrapper like dbIn() allows us to change the way our function works internally and cascade that change to our entire site.

Database Connectivity inside conn_inc.php: All MySQL credentials are stored in an include file named conn_inc.php.  This file houses a function named conn(), which when called will connect to MySQL via credentials provided.  If no data is entered, the default level of access admin is used.

Inside the function, in lessening order of access, are the following designated sets of MySQL credentials:

Access Level

Notes

admin

Full db access, no limitations, includes alter, drop, index, etc. including below

delete

Use this likely for admins only.  However, usually we don’t delete, just archive data.

insert

Use this to add a new profile, plus update existing, and view data.

update

User could for example only read or update their data, for example their profile.

select

Read access only.  No ability to change data in any way.  Great for the public, esp. site search

Each designated credential set should include the capabilities of the credentials below.  The following relies on you creating MySQL users with the exact capabilities identified.  This is not automatically done.  The idea is that we use the lowest level of access necessary for the particular connection and thereby curb the possibility of SQL Injection Attack.

There will be times when we will connect several times to the database on the same page.   To do this repeatedly is an unwise use of resources, so we have a class named IDB inside conn_inc.php file that will allow us to share a single connection, once one is created.  To do this we create a singleton class that relies on the keyword static to be sure that if the class has been created once on a page, it is reused.  To create a shared connection, you can call the class in this way:

$iConn = IDB::conn(); #creates shared mysqli connection

You can then use this same $iConn variable as a mysqli (improved) connection (or call the class again) as many times on the page as you wish and the connection is shared as long as you have not explicitly closed the connection with the mysqli_close() command.

PHP Include Folder: All 3 files end in "_inc.php" to indicate they belong in an include folder.  All our include files will be stored in a folder named inc_0700, which is so named to indicate all contents should receive a 0700 permission, if possible.  We'll store the path to our include files as a constant named INCLUDE_PATH, which will be the physical path as seen from the inside so PHP can immediately know where to look for these files.  This is both secure and efficient as the PHP path is thus hard wired and unchangeable via code.    If your server doesn't provide space outside a web root, you can target any path.

We'll still need an include folder inside the web root for CSS and JavaScript include files, as these require a virtual path, and can't use the physical path reference we'll use for PHP files.  This path will be stored as a constant named VIRTUAL_PATH and allow us to 'hard wire' a path to all web assets (images, CSS, JS files) as these must be in the web root to work with the browser.  By doing this we can now place our files in any folder inside our web root and all include files & assets will be available.  This later allows us to re-write our virtual paths via a process called mod_rewrite so we can present search engine friendly URLs.

Referencing config_inc.php:

Once we have our functional include files set up, we need to reference config_inc.php:

require 'inc_0700/config_inc.php';

Note there is a relative path reference (like a typical image file) in this case.  We use the PHP require() function as a replacement of the include() function.  This is because we don't want any code on our page to proceed if this file is not present.  We will be sure however to not use include_once() because all of the "_once()" variations check to be sure no similar code exists before proceeding, which in our case will slow down the page a bit. 

nmCommon Package: All of these include files provide a 'kit' for starting to build a dynamic PHP web application.  Such a 'kit' is often called a 'package' in software parlance.  Since these files are 'common' meaning contained in all other files we'll call our package nmCommon.

Our include files together with installation instructions are included in the Zip file below.  Download this zip file and read the instructions prior to installation: 

nmCommon Package

 

Demo Pages: Also in nmCommon are demo pages which we can use as starting points for building web applications.   For a simple page, you can use index.php.  For database pages there are three versions, one for a mysql classic connection, one for a mysqli improved connection and one for a mysqli shared connection.  Also included is an altered version of contact.php (named model_contact.php) which is an updated version of reCAPTCHA contact page.  In this page particularly you will need to update the email info. 

Once your model pages are all working, you can select the model page (or any other) that most closely matches the requirements of a page you wish to build.  To use a model page, simply copy the page, rename it and begin building your new application.

Self Documenting Code: You may notice some odd handling of 'comments' in these example pages. On the top of the common_inc.php page for example is a set of comments like this:

/**
 * common_inc.php stores site-wide utility functions
 *
 * Stores functions like myerror(), which handles MySQL and other
 *  or die() errors, myRedirect() to direct users away from pages and 
 *  dbOut() which cleans data coming from MySQL
 *
 *
 * @package ITC280
 * @author Bill Newman <williamnewman@gmail.com>
 * @version 1.0 2008/05/01
 * @link http://www.newmanix.com/itc280/
 * @license http://opensource.org/licenses/osl-3.0.php Open Software License ("OSL") v. 3.0
 * @todo none
 */

These pages are designed to 'self-document' when used with a PHP documentation program such as PHPDocumentor. We explore these in detail in the ITC281 class. However, look at what the PHPDocumentor can do to our pages: SELF DOCUMENTED SITE SAMPLE

Print this Page Back To Top

© 2000- 2012 newMANIC INC, All rights reserved