File Inclusion
You may need a set of code to be executed in multiple pages and copying the same code on all pages may consume time and also reduce the code efficiency as in case of a small change to that code you may need to change it in all pages. This problem can be overcome with the help of file inclusion methods provided by PHP.
File inclusion methods are used to include one PHP file into another. It takes all the code from the specified PHP file and copies it to the file carrying inclusion method. This process occurs before the execution of code. These are :
include
require
// syantax
include "filename";
// or
require "filename";
Both of the above functions are similar except for their behaviour on error where, include
will just generate a warning i.e. E_WARNING
and script will continue. On the other hand, require
will generate an error i.e. E_COMPILE_ERROR
and script will stop.
Apart from these both include and require can be used as:
include_once
require_once
// syantax
include_once "filename";
// or
require_once "filename";
Similarity between include_once and require_once:
Its behaviour is similar to that include method except for the fact that if the statements of the file are already included in the corresponding file then they will not be included again.
Difference between include_once and require_once:
Alike include method, include_once
will just produce a warning and will continue to execute the script whereas require_once
will throw an error and stop executing the script.
For Example: Suppose we are having all over common footer content (shown as below) in our website and having the following content.
<footer>
<?php
echo "<h5>Copyright © 2005 - ".date("Y")." abc.xyz</h5>";
?>
</footer>
We will create a file as footer.php
in the project folder and copy this footer content in that footer.php
and save the file.
Now, instead of putting same content all over the web pages, we can simply call footer.php in those web pages. as below:
// homePage.php
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
Body content here.
<?php
include “footer.php”; // or you can use require “footer.php”;
?>
</body>
</html>
In result, if we make any changes to this footer.php
file, those changes will reflect all over other webpages whereever footer.php file has been called.
Note*: Suppose a case, footer.php
file does not exist. In that case, if we use the include
statement, the script will still continue to execute. On the other hand, if we use the require
statement, the script execution will stop.