Through functions, We can include the content of one PHP file into another PHP file before the server executes it.
(i) include()
(ii) require()
Example:- In this eg. we have 2 files
(i) topmenu.php
(ii) index.php
in this eg. topmenu file included in the index.php file
(i) topmenu.php
<div>
<div><a href="home">Home</a></div>
<div><a href="contactus">Contact Us</a></div>
</div>
(ii) index.php
<?php
<html>
<body>
<div class="topmenu">
<?php include 'topmenu.php';?>
</div>
<div>Welcome to My site</div>
</body>
</html>
?>
Difference between include() and require()
Include():- If an error occurs, the include() function generates a warning, but the script will continue execution.
require():- If an error occurs, the require() function generates a fatal error, and the script will stop.
include_once():- The include_once function is exactly the same as the include function except it will limit the file to be used once.
example:- I have include content.php file in the for loop and file will be include only one time. but loop will run four times.
<?php
for($i=1;$i<5;$i++)
{
include_once('content.php');
}
?>
If we use include() function in the for loop and file will be include 4 times.
<?php
for($i=1;$i<5;$i++)
{
include('content.php');
}
?>
Note:- require() and require_once() will be same work as a include() and include_once();
Ques:- Can we use include one file, more than one times in a PHP page?
Ans:- Yes we can use include one file, more than one times in any page.
Example:- We have 3 files (1) employee1.php (2) employee2.php (3) index.php
In employee1.php [php]
In employee2.php [php]
(1) We include employee1.php in the index.php 2 times.
<?php
include('employee1.php');
include('employee1.php');
?>
this file show employee1 information
(1) We include employee2.php in the index.php 2 times.
<?php
include('employee2.php');
include('employee2.php');
?>