Including files

Including files in PHP allows to insert (and evaluate if it is PHP code) the contents of another file into your page.


This can be used, for example, to keep common page elements - headers, footers, menus, etc, in separate files and include them in your pages. As a result when you update the files the changes take effect across the whole of your website.

There are 4 different functions which can be used to include files and they are:

  • include
  • include_once
  • require
  • require_once

They are all very much the same in the way they include the contents of the files but differ slightly in how they handle errors and multiple calls.

The code

To include the file foo.php you would use the following PHP code:

<?php
include 'foo.php';
?>

The location of the file you want to include should be relative to the file you are including it into. In the above example, foo.php should be in the same directory as the file that contains the example code.


You can include any type of file, if it is a valid PHP file it will also be parsed. This all happens server side so the final page as viewed from the browser will appear as a single HTML webpage.

Require

require works the exact same as include the only difference is in how it handles errors. If you try to include a non-existent file using include an error will be outputted however PHP will continue to run the other code (an E_WARNING), however if you use require to include the same file PHP will stop executing altogether (a fatal error). You should use require when the contents of the file are needed for the rest of the code to run otherwise include will suffice.

require_once and include_once

require_once and include_once work the same way as their require and include relatives in terms of functionality. The difference is that if the same file attempted to be included/required again it will be ignored:

<?php
include_once 'foo.php'/* will include the contents of foo.php */
include_once 'foo.php'/* will be ignored */
?>

And that concludes including files with PHP!