PHP Include Files
PHP include and require Statements
In PHP, you can insert the contents of a file into a PHP file before the server executes it.
The include and require statements are used to insert useful code written in other files into the flow of execution.
include and require are identical except for how they handle errors:
require produces a fatal error (E_COMPILE_ERROR) and stops the script execution if an error occurs.
include produces a warning (E_WARNING) and the script continues execution if an error occurs.
Therefore, if you wish to continue execution and output results even if the included file is missing, use include. Otherwise, in frameworks, CMS, or complex PHP application programming, always use require to reference critical files in the execution flow. This helps improve the security and integrity of the application in case a critical file is accidentally lost.
Including files saves a lot of work. This means you can create standard header, footer, or menu files for all web pages. Then, when the header needs updating, you only need to update this header include file.
Syntax
include 'filename';
or
require 'filename';
PHP include and require Statements
Basic Example
Suppose you have a standard header file named "header.php". To reference this header file in a page, use include/require:
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Example 2
Suppose we have a standard menu file used on all pages.
"menu.php":
echo '<a href="/">Home</a>
<a href="/html">HTML Tutorial</a>
<a href="/php">PHP Tutorial</a>';
All pages on the website should reference this menu file. Here is how:
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Example 3
Suppose we have an include file that defines variables ("vars.php"):
<?php
$color='red';
$car='BMW';
?>
These variables can be used in the calling file:
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<h1>Welcome to my home page!</h1>
<?php
include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>
</body>
</html>