PHP Include/Require Function

The include/require statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.

Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.

Both Include/Require Statements are identical except errors.

  • Require will produce fatal error and stop the script.
  • Include will produce warning message and continue the execution of script.

require_once & include_once is another identical versions of both functions with the feater of one time file include. both are recommend method's during high end application development.

Division of page

Majority of web applications consist of same headers, menus, footer. so in the below example we will identifiy the gerneric parts of web page and divide into header, menu and footer files and include them in a web pages.

<!doctype html>
			<!--Head Starts Here-->
	<head>
		<title>Include/Require Functions</title>
	</head>
		<!--Head Ends Here-->
	<body>
		<!--Menus Start Here-->
		<a href="#">Home</a>
		<a href="#">HTML</a>
		<a href="#">CSS</a>
		<a href="#">Java Script</a>
		<!-- Menus End Here-->
		<br />
		<h1>Welcome to PHP Docs</h1>
		<p>This example will divide header, menus, footer into separate files</p>
		<!--Footer Starts Here-->
		<?php echo "<p>Copyright © 2017-" . date("Y") . " PHPdocs.com</p>"; ?>
		<!--Footer Ends Here-->
	</body>
</html>

Above Web Page common parts are marked with comments. below we will create the separate files for each part and include them in final page

Header Part

Copy the Header part and save in header.php file.


		<!--Head Starts Here-->
	<head>
		<title>Include/Require Functions</title>
	</head>
		<!--Head Ends Here-->

Menu Part

Copy the Menu Part and save in menu.php file.


		<!--Menus Start Here-->
		<a href="#">Home</a>
		<a href="#">HTML</a>
		<a href="#">CSS</a>
		<a href="#">Java Script</a>
		<!-- Menus End Here-->

Footer Part

Copy the Footer Part and save in footer.php file.


		<!--Footer Starts Here-->
		<?php echo "<p>Copyright © 2017-" . date("Y") . " PHPdocs.com</p>"; ?>
		<!--Footer Ends Here-->

Join the Pages with include_once/require_once

Now combine the all divide files in a web-page to get the final output.

<!doctype html>
		<!--Including using require_once header.php-->
		<?php require_once 'header.php'; ?>
	<body>
		
		<!--Including using require_once menu.php-->
		<?php require_once 'menu.php'; ?>
		
		<br />
		<h1>Welcome to PHP Docs</h1>
		<p>This example will divide header, menus, footer into separate files</p>
		
		<!--Including footer.php-->
		<?php include_once 'footer.php'; ?>
	</body>
</html>

Benefit of this method is to make things generic. for example your website have 50 pages with more then 50+ links. if you want to change any link then what ? if you are using this generic method only need to change the menu from one place instead of modifying 50 pages.