PHP Include and Require

When creating a website using PHP it is often necessary to have identical sections of code on multiple pages. An example of this would be connecting to a MySQL database, where each page needs to extract or amend data stored within it. If the PHP for connecting to the database existed within each page and something change, such as the database password, then the password on each page would have to be changed.

To resolve this, the PHP for connecting to a MySQL database, as in this example, could be in one PHP file and then this file could be incorporated in to however many pages is necessary. The advantage with this is that when anything needs to be changed, such as the password, it only needs to be done in one place. This can be done using the 'include' and 'require' statements.

include ("file-name.php");

require ("file-name.php");

If the file to be included doesn't reside in the same location as the web page, then the path would need to be included.

include ("/include-path/file-name.php");

require ("/include-path/file-name.php");

The difference between 'include' and 'require' is in their handling of an error when the file to be included does not exist. With the 'include' statement, if the file does not exist, a warning is produced and execution of the PHP script continues, however, with the 'require' statement, a fatal error is produced and execution of the PHP script stops.

Variations on the 'include' and 'require' statements are the 'include_once' and 'require_once' statements. 

include_once ("file-name.php");

require_once ("file-name.php");

These statements do the same job as their corresponding 'include' and 'require' statements, except that they do a check to see if the file has been included before and if so does not include them again. Connecting to a database is a good example of when to use these statements because it is only necessary to connect once within a page, unless the connection has been closed.