PHP Include Files
When you wish to utilize the same PHP, HTML, or text file on several pages of a website, including files is quite beneficial.
Include files are reusable components.
PHP offers include
and require
statements which you
allow to reuse files in your website.
PHP include and require Statements
The include
or require
statement can be used to include or import
the content of a file into another PHP file (before the server runs it).
The both statements are same or identical but with a little different.
- The
require
statement will include the content of specified file if it found, otherwise it will generate a fatal error (COMPILE ERROR) and the script will be terminated. - The
include
statement will include the content of specified file if it found, otherwise it will generate an error (WARNING), and the script will continue to run.
Including files are very useful in many situations. A website can have common things in many pages like:
- Header
- Footer
- Side Menu Links
- Others
Note:- These above mentioned itesms are used almost every pages in a website.
Syntax :-
include 'filename';
or:-
require 'filename';
Related Links
PHP include Examples
Use the include
statement if you want the execution to continue and display
the results even if the specified file is missing. Otherwise, always utilize the require
statement to include a vital file in the flow of execution.
Example 1 :- Assume we have a file called "footer.php" with the following contents :
Copyright © 2012-" . date("Y") . " Simmanchith.com";
?>
To include the footer.php file in a php page called "demo.php", use the
include
statement:
Welcome to my page!
Some text.
Some more text.
Output :-
Welcome to my home page!
Some text.
Some more text.
Copyright © 2012-2024. Simmanchith.comNote:- You can include not only the contents of a file and also PHP programming variables, functions, and classes.
Example 2 :- Let's assume we have a file called "vars.php" that contains some php variables:
The variables can then be used in any php file if we include "vars.php" file.
Welcome to my home page!
Output :-
Welcome to my home page!
I have a red BMW.";PHP include vs. require
A file can also be included in PHP code using the require
statement.
Example 1 :- There is also a huge distinction between include and require: if the include
statement contains a file and PHP cannot find the file, then the script is still running :
Welcome to my home page!
Output :-
Welcome to my home page!
HiExample 2 :- If we use the require
statement to utilize the same example, the echo
state will not be executed since the script execution terminates after a fatal error was returned by the require
statement :
Welcome to my home page!
Output :-
Welcome to my home page!
Use require
when the application requires the file.
When the file isn't needed, use include
, and if the file isn't discovered, the application should proceed.
Related Links