Free Beginner PHP Tutorials - Include and require functions
2016/10/06 / Science and Tutorials
Learn how to insert the content of one PHP file into another PHP file using the include or require functions.
What is PHP include and require Statements?
This is a function that allows adding the content of a PHP file into another PHP file.
They take all the text that exists in the specified file and copies it into the file that uses the include or require function.
They are reusable time to time in different parts of the web pages. For example, including header, footer. Mostly, they work like functions and thus reduce the time used to develop a web page.
There are two PHP functions which can be used to include one PHP file into another PHP file.
1. Include() Function
2. Require() Function
The include() Function and require() function work alike however on failure.
require() function will generate a fatal error (E_COMPILE_ERROR) and the execution of the code terminates when the file which is required is not found and no more output generates.
include() function will produce a warning (E_WARNING), and the execution of the code will continue beside the file to be included is not found
The include and require functions can also be written as statements as shown below and perform the same task as the other
<?php include('filename'); or require('filename'); ?>
<?php include 'filename'; or require 'filename'; ?>
For example, assume we have a file 'header.php', that looks like this;
<?php echo "<p> Whats-online.info: Best IT blog at all time</p>"; ?>
To add the above file 'header.php,' to another file, use the include function or require function as shown below.
<html> <body> <p>Follow us on Facebook, Twitter, Google Plus<p> <?php include('header.php');?> <p>Welcome to whats-online.info!</p> <p>Hey Guys whatsapp.</p> <p>Here cometh thee.</p> </body> </html>
<html> <body> <p>Follow us on Facebook, Twitter, Google Plus<p> <?php require('header.php');?> <p>Welcome to whats-online.info!</p> <p>Hey Guys whatsapp.</p> <p>Here cometh thee.</p> </body> </html>
If the file exists, the output will be:
Follow us on Facebook, Twitter, Google Plus
Whats-online.info: Best IT blog at all time
Welcome to whats-online.info!
Hey Guys whatsapp.
Here cometh thee.
In case, the file to be required or included is not found; the following errors are generated
Include function warning
The code is executed no matter the case, however, a warning is generated as shown below.
Require function error.
Only, the code above the required file is executed, however, the execution below the required file is halted, and an error is generated as shown below
Use require function when the application requires the file.
Use include function when the file is not required, and application should continue when the file is not found.