PHP include files
In PHP, you can insert the contents of a file into the PHP file before it is executed by the server. The
include and requirestatements are used to insert useful code written in other files into the execution flow.
include and require are identical except for how they handle errors:
requiregenerates a fatal error (E_COMPILE_ERROR), The script willstop executingafter an error occurs.
includeGenerate a warning (E_WARNING), and the script willcontinue executionafter the error occurs.
So if you want to continue execution and output the results to the user even if the included file is missing, then use include. Otherwise, in frameworks, CMS, or complex PHP application programming, always use require
to reference key files in the execution flow (from one statement to the next, until the end of the program is run). This helps improve application security and integrity in the event that 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 pages. Then, when the header needs updating, you simply update the header include file.
Syntax
##include"filename";
orrequire"filename";
##Instance
Assume there is a file named header.php, as follows
Use include to include the header.php file
PHP中文网
Program running result:
Welcome to the PHP Chinese website to learn PHP
Instance
There is one Standard menu file named "menu.php":
首页 - HTML 教程 - CSS 教程 - JavaScript 教程 - PHP 教程'; ?>
Use "require" to include the "menu.php" file
PHP中文网 欢迎来到PHP中文网
Program Running results:
Welcome to PHP Chinese websiteHomepage-HTML Tutorial-CSS Tutorial-JavaScript Tutorial-PHP Tutorial
include VS require##There is a huge difference between include and require: if a file is referenced with an include statement and PHP cannot find the file, the script willcontinue execution
.If we use the require statement to complete the same case, the echo statement will not continue execution because the script willterminate execution after the require statement returns a serious error
Example
## Use include to include non-existent files
Program running result:PHP中文网 欢迎来到PHP中文网
Welcome to PHP Chinese website
I'm learning
Use require to include non-existent files
PHP中文网 欢迎来到PHP中文网
Program running result:
Welcome to PHP Chinese websiteAttention
: When using include and require to include a non-existent file, a warning message may appear. This is the error level you can set in php.ini
-
Open php.ini
- Ctel+F search error_reporting
- Find error_reporting = E_ALL
- Replace error_reporting = E_ALL into error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_WARNING
- ##Restart Apache
##