Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP include and require

PHP Including Files


PHP include and require Statements

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

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 how they handle errors:

Therefore, if you want to continue execution and output results to the user 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';

或者

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:





Runoob Tutorial(runoob.com)




欢迎来到我的主页!

一些文本。

Example 2

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

"menu.php":


echo '主页
HTML 教程
PHP 教程';

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





Runoob Tutorial(runoob.com)



欢迎来到我的主页!

一些文本。

Example 3

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



These variables can be used in the calling file:





Runoob Tutorial(runoob.com)



欢迎来到我的主页!