To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the user of functional cookies. For more information read this page.

PHP 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.

include

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 method that performs a similar function. Both of these methods 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 function 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:

PHP
<?php
	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 function is that if the code needs to be updated, only that file is changed.

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

include_once

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

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

Similar functions

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