PHP Include and Require
PHP allows us to create various elements and functions, which are used several times in many pages. It takes much time to script these functions in multiple pages. Therefore, use the concept of file inclusion that helps to include files in various programs and saves the effort of writing code multiple times. "PHP allows you to include file so that a page content can be reused many times. It is very helpful to include files when you want to apply the same HTML or PHP code to multiple pages of a website." There are two ways to include file in PHP.
- include
- require
Both include and require are identical to each other, except failure.
- include only generates a warning, i.e., E_WARNING, and continue the execution of the script.
- require generates a fatal error, i.e., E_COMPILE_ERROR, and stop the execution of the script.
Advantage
PHP include
PHP include is used to include a file on the basis of given path. You may use a relative or absolute path of the file.
There are two syntaxes available for include:
Syntax
include 'filename ';
Or
include ('filename');
Let's see a simple PHP include example.
File: menu.html
PHP Example
<a href="http://www.javatpoint.com">Home</a>|
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: include1.php
PHP Example
?php include("menu.html"); ?>
<h1>This is Main Page</h1>
Output
PHP require
PHP require is similar to include, which is also used to include files. The only difference is that it stops the execution of script if the file is not found whereas include doesn't.
Syntax
There are two syntaxes available for require:
Syntax
require 'filename';
Or
require ('filename');
Let's see a simple PHP require example.
File: menu.html
PHP Example
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: include1.php
PHP Example
?php include("menu.html"); ?>
<h1>This is Main Page</h1>
Output
PHP include vs PHP require
Both include and require are same. But if the file is missing or inclusion fails, include allows the script to continue but require halts the script producing a fatal E_COMPILE_ERROR level error. Let's understand the difference with the help of example:
Example
PHP Example
<?php
//include welcome.php file
include("welcome.php");
echo "The welcome file is included.";
?>
Output
PHP Example
<?php
echo "HELLO";
//require welcome.php file
require("welcome.php");
echo "The welcome file is required.";
?>