Require () and Include () function in PHP

The Include() and require() statements are used to insert codes written in other files, in the flow of  execution.

The main of using include and require functions to integrate one page code or content into another page. You can maintain usually some repeated functionality in the form of PHP file and finally you can call it wherever you want.

See, the following example demonstrates how to integrate a menu content in other pages of PHP. There is a page in menu.php and it can be included in some other pages of the website.

Menu.php

<a href=”index.php”>Home</a>
<a href=”services.php”>Services</a>
<a href=”about.php”>About Us</a>
<a href=”contact.php”>Contact Us</a>

The following page index.php uses above menu.php content. See the below code how it follows

<head>

<title>My Web page</title>

</head>

<body>
<?php

include  “menu.php “;

?>
</body>

Difference between Include and require:

The main difference between include and require statements in PHP is that if any error occurred include will raise an error message and then will continue the rest of the code placed in the page where as require will raise a fetal error and terminates execution.

  • Function require () throws an error (E_COMPILE_ERROR) and stop the script.
  • Function include () throws a warning (E_WARNING) but the script will continue.

 

require_once()

function require_once is useful if the result of the code is necessary but subsequent inclusions would throw an error. That goes for scripts with functions for instance. If such a script would be included more than once an error would be thrown since functions cannot be redeclared.

 

include_once()

Function include_once  is useful in the case of including remote files and not wanting them to be included several times due to an HTTP overhead. This is also usefull in payment gateway and process on e-commerce websites.

Examples

<head>

<title>My Web page</title>

</head>

<body>

<div class=”header”>
<?php

Include_once  “menu.php “;

?>

</div>

<div class=”footer”>

<?php

Include_once  “menu.php “;

?>

</div>

</body>

In this example you will see warning when you attempt to recall file “menu.php”