File Inclusion In PHP



File inclusion in the PHP is one of the most usefull function, by which you can include the content of a PHP file into another PHP file before it is executed by the server. With file inclusion you can create the header,footer,left sidebar,right sidebar and includes all these into one PHP file. This is helpful for the developers to change the layout of complete website with minimal effort easily. If there is any change required into the existing site then there is no need to change thousand of files just made the changes into the included file only. This can be done by using the PHP function given below:

1. include() Function
2. include_once() Function
3. require() Function
4. require_once() Function

PHP include() Function :

The include() function includes all the text which is specified into the file and copies the content run time into the file that uses the include function. If there is any problem into the included files then the include() function generates a warning but the script executes continuously. Code inside the included file will then run when the include function is called. It takes only one argument that is the file path you want to include.

<?php

	include 'header.php';

?>

You can includes many files on a single file i.e.

<?php
	include 'header.php';
	include 'left_sidebar.php';
		<div id="content"> Your Content Part Is Here</div>
	include 'footer.php';
?>

PHP include_once() Function :

It is just like as the PHP include() but the differences is that it will includes the file only once.

<?php

foreach($values as $pr_data)
{
    include_once 'products.php';// This will includes this file only once
}

?>

PHP require() Function:

As per the name require, means when you are including any file by using the require(), the file is required for the application to work correctly, other wise it will throw a PHP error and stops the scripts executions.

<?php
	require 'main_page.php';
?>

PHP require_once() Function:

require_once() is the combination of the require and include_once function. Means it will make sure that the file exists before adding it to the page if the file is not there it will throw a fatal error, and it will make sure that the file can only be used once on the page.

<?php
	require_once 'header.php';
	require_once 'left_sidebar.php';
		<div id="content"> Your Content Part Is Here</div>
	require_once 'footer.php';
?>

This is all about the PHP file inclusion, hope this will be helpfull. Thanks and enjoy the reading.