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 include '
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:
<body>
<?php include ' header.php ';?>
<p>some text.</p>
</body>
Suppose we have a standard menu file that is used on all pages.
"Menu.php":
Echo ' <a href= "/default.php" >Home</a>
<a href= "/tutorials.php" >Tutorials</a>
<a href= "/references.php" >References</a>
<a href= "/examples.php" >Examples</a>
<a href= "/about.php" >about us</a>
<a href= "/contact.php" >contact us</a> ';
All pages in the site should refer to the menu file. Here are the specific practices:
<body>
<div class= "Leftmenu" >
<?php include ' menu.php ';?>
</div>
<p>some text.</p>
</body>
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:
<body>
<?php include ' vars.php ';
echo "I have a $color $car"; I have a red BMW
?>
</body>
PHP include and require