PHP include and Require statements
In PHP, you can insert the contents of a file in a file before the server executes the PHP file.
The Include and require statements are used to insert useful code that is written in other files in the execution stream.
Include and require are the same in other ways except for handling errors:
- Require generates a fatal error (E_COMPILE_ERROR), and the script stops executing after the error occurs.
- Include generates a warning (e_warning) that the script will continue to execute after the error occurs.
Therefore, if you want to continue execution and output the results to the user, use include if the included file is missing. Otherwise, in framework, CMS, or complex PHP application programming, always use require to reference critical files to the execution stream. This helps improve the security and integrity of your application in the event that a critical file is accidentally lost.
The inclusion of files saves a lot of work. This means that you can create a standard header, footer, or menu file for all pages. Then, when the page header needs to be updated, you only need to update the header include file.
Grammar
' filename '; or require' filename ';
PHP include and require statement base instances
Suppose you have a standard page header file named "header.php". To refer to this page header file in the page, use Include/require:
<meta CharSet="Utf-8"><title> Beginner's Tutorial (runoob.com)</title><body><? php include ' header.php '; ?>Welcome to my homepage! <p> some text. </p></body>
Example 2
Suppose we have a standard menu file that is used on all pages.
"Menu.php":
' <a href= '/' > Home </a><a href= '/html ' >html tutorial </a><a href= '/php ' >php tutorials </a> ';
All pages in the site should refer to the menu file. Here are the specific practices:
<meta CharSet="Utf-8"><title>Beginner's Tutorial (runoob.com)</title><body><div class="Leftmenu"><? php include ' menu.php '; ?></div>Welcome to my homepage! <p> some text. </p></body>
Example 3
Suppose we have a containing file ("vars.php") that defines a variable:
<? php$color=' red '; $car=' BMW ';? >
These variables are available in the calling file:
<meta CharSet= "utf-8" >< Title> Rookie tutorial (runoob.com) </title><body> Welcome to my homepage! <? ' vars.php ' ; "I have a $color $car" ;//I have a red bmw?> </body></HTML>
PHP include and require