Web Development Tutorials


Include files

The ability to reuse existing code is important because it can save time, money, and promote consistency. Suppose a web site contains a menu section that is repeated on each page. Instead of re-coding the menu, it would be much easier to code the menu once and dynamically include the menu contents on each of the individual web pages. This is possible using what are known as server-side include files.

Include files can contain any HTML or PHP code and are commonly saved with the extensions .php, .txt, or .html. The contents of an include file are coded once and included in as many PHP pages as needed. If a change is made to an include file, the updates are automatically reflected on all of the PHP pages referencing the include file.

Below is an example of a typical include file containing page header information:


  Welcome to WebTutorials.com.

This example shows an include file called header.php. The file contains the text "Welcome to WebTutorials.com." surrounded by the HTML <h3> tag. This creates a level three header that can now be included on all of the pages that make up the WebTutorials site.

After an include file is created, it can be included within a PHP page using one of the following functions:

  require(filename) - includes and evaluates the specified file

  include(filename) - an alias of require()

One key difference between the require() and include() functions is that when include() cannot locate the referenced file, it returns a warning. On the other hand, require() returns a fatal error.

In the next example, the header.php file is included within an existing PHP page:


   echo "<p>This is the WebTutorials site...</p>";

The require() function calls the header.php file and evaluates the contents of the file. The contents are then displayed as if they are apart of the home.php page. In this example, the require() function is coded at the top of the page since it contains header information. The require() statement can, however, be included anywhere within a PHP document. The location of the require() function determines where the contents of the .php file will be displayed within the context of the PHP page.

  Welcome to WebTutorials.com.
  This is the WebTutorials site...

It is important to note that when using include files that contain confidential information such as passwords or user information, the files should be saved using the .php extension and not .inc or other nonstandard extension. Files that use nonstandard file extensions can be downloaded from the Web server and the contents can be viewed as plain text. Using the .php extension ensures that the client will not be able to view the source code, only the HTML code returned by the server.

TOP | NEXT: Using Functions