Including files is very useful when you want to include the same text, HTML, or PHP file on multiple pages of a website. It is possible to insert the content of one PHP file into another PHP file with the include or require statement.
The include and require statements are identical, except:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script.
include will only produce a warning (E_WARNING) and the script will continue.
Example 1: Assume we have a standard header file called "header.php"
<?php echo "<h1> Website Heading </h1>"; <hr /> ?>To include the header file in a page, use the include statement:
<html> <body> <?php include 'header.php';?> <h1>Welcome to my home page!</h1> <p>Some text.</p> <p>Some more text.</p> </body> </html>Example 2: Assume we have a standard menu file called "menu.php":
<html> <body> <div class="menu"> <?php include 'menu.php';?> </div> <h1>Welcome to my home page!</h1> <p>Some text.</p> <p>Some more text.</p> </body> </html>
The require statement is also used to include a file into the PHP code. However, there is one big difference between include and require, when a file is included with the include statement and PHP cannot find it, the script will continue to execute:Example:
<html> <body> <h1>Welcome to my home page! </h1> <?php require 'noFileExists.php'; ?> </body> </html>