PHP Include Files


PHP include and require statements

In PHP, you can insert the content of one file into another PHP file before the server executes it.

The include and require statements are used to insert useful code written in other files into the execution flow.

include and require are identical in every way except for how they handle errors:

  • require generates a fatal error (E_COMPILE_ERROR), and the script stops executing after the error occurs.
  • include generates a warning (E_WARNING), and the script continues executing after the error occurs.

Therefore, if you want execution to continue and show output to users 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 into 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 the header include file.

Syntax

include 'filename';

或者

require 'filename';

PHP include and require statements

Basic Examples

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>Example(example.com)</title>
</head>
<body>

<?php include 'header.php'; ?>
<h1>欢迎来到我的主页!</h1>
<p>一些文本。</p>

</body>
</html>

Example 2

Suppose we have a standard menu file used on all pages.

"menu.php":

echo '<a href="../index.html">主页</a>
<a href="../html.html">HTML 教程</a>
<a href="../php.html">PHP 教程</a>';

All pages on the website should reference this menu file. Here is how to do it:

<html>
<head>
<meta charset="utf-8">
<title>Example(example.com)</title>
</head>
<body>

<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
<h1>欢迎来到我的主页!</h1>
<p>一些文本。</p>

</body>
</html>

Example 3

Suppose we have an include file ("vars.php") that defines variables:

<?php
$color='red';
$car='BMW';
?>

These variables can be used in the calling file:

<html>
<head>
<meta charset="utf-8">
<title>Example(example.com)</title>
</head>
<body>

<h1>欢迎来到我的主页!</h1>
<?php 
include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>

</body>
</html>
Other Extensions