Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 5.1PHP includes

Part 5.1PHP includes

HTML becomes a burden when every page needs updated with something like a change in the menu.

PHP, being a server side language, can generate this code for you, but then the problem is still there if the code needs to be changed on every page.

Reusable PHP is a very handy way of saving on server space. By duplicating PHP, the amount of space being used doubles. This can be fully avoided, as with any programming language such as C or Java.


In PHP, reusing code is achieved using the include method.

include in PHP could be seen as a more advanced version of the file_get_contents function that performs a similar function. Both of these can read any type of file and turn it into something to use, but the difference is that if the file_get_contents function is used on a PHP file, it will read the PHP file as text whereas the include construct will include the PHP as executable PHP (and will execute it).

The following example demonstrates a page which uses another page found at 'php/login.php' which contains functions such as the isLoggedIn function:

	include "php/login.php";
	$isLoggedIn = isLoggedIn();

	if ($isLoggedIn)
		echo "<h2>New articles</h2>";
		echo "<p>Our articles are shown below:</p>";
		//TODO: Need to include some access to the database
		echo "All articles are copyright";

The main advantage of using the include construct is that if the code needs to be updated, only that file is changed.

As the entire file is included with the include construct, all variables and functions that are defined will also be included along side the values they have.


PHP also has another very similar function to the include construct - include_once.

Although both work nearly identically, there is a key difference in that the include_once construct prevents the same file being included more than once. The include construct on the other hand will overwrite the original include.

Similar functions

There also exists a require construct and a require_once construct. Both of these constructs work exactly the same way as the include constructs except that when an error occurs, instead of throwing a standard PHP warning, they throw a compile error thus stopping script execution.

Feedback 👍
Comments are sent via email to me.