PHP Include Files
Posted By
Bajarangi soft ,
Posted On 01-02-2024
PHP allows you to include file so that a page content can be reused many times.
Include Files In PHP
The ‘include’ or ‘require’ statement can be used to insert the content of one PHP file into another PHP file (before the server executes it).
Including files is very useful when you want to include the same PHP, HTML, or text on 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 upon failure.
- require will produce a fatal error (E_COMPILE_ERROR) and stop the script.
- include only generates a warning, i.e., E_WARNING, and continue the execution of the script.
If the include statement appears, execution should continue and show users the output even if the include file is missing. Otherwise, always use the required declaration to include the main file in the flow of execution while coding Framework, CMS, or a complex PHP program. This will help prevent the application's protection and reputation from being jeopardized if one key file is corrupted.
Syntax :
include("path/to/filename"); -Or- include "path/to/filename";
require("path/to/filename"); -Or- require "path/to/filename";
Example :
Now, assume that we have php file called 'variables.php' like this,
<?php
$a =10;
$b = 5;
?>
and second file is 'addition.php' where we incleded 'variable.php' file,
<?php
include 'variable.php';
<h2> addition of two variable </h2>
$c = $a + $b ;
echo $c;
?>
output :
addition of two variable
15
If we do the same example using the require
statement, the echo statement will not be executed because the script execution dies after the require
statement returned a fatal error:
<?php
require'variable.php';
<h2> addition of two variable </h2>
$c = $a + $b ;
echo $c;
?>
output :
addition of two variable