In PHP, you can insert the contents of a file into the PHP file before it is executed by the server.
The include and require statements 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:
require generates a fatal error (E_COMPILE_ERROR), after which the script stops executing.
include generates a warning (E_WARNING) and the script continues execution after the error occurs.
Therefore, if you wish to continue execution and output 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 to the execution flow. 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 web pages. Then, when the header needs updating, you simply update the header include file.
include 'filename';or require 'filename';
Suppose you have a standard header file called "header.php". To reference this header file in the page, please use include/require:
<html><head><meta charset="utf-8"><title>Coder Tutorial (codercto.com)</title></head><body><?php include 'header.php'; ?> <h1>Welcome to my homepage!</h1><p>Some text. </p></body></html>
Let's say we have a standard menu file that is used across all pages.
"menu.php":
echo '<a href="/">Homepage</a><a href="/html">HTML Tutorial</a><a href="/php">PHP Tutorial</a>';
All pages in the website should reference this menu file. Here’s how to do it:
<html><head><meta charset="utf-8"><title>Coder Tutorial (codercto.com)</title></head><body><div><?php include 'menu.php' ; ?></div><h1>Welcome to my homepage!</h1><p>Some text. </p></body></html>
Let's say we have an include file ("vars.php") that defines variables:
<?php$color='red';$car='BMW';?>
These variables are available in the calling file:
<html><head><meta charset="utf-8"><title>Coder Tutorial (codercto.com)</title></head><body><h1>Welcome to my homepage!</h1> h1><?php include 'vars.php';echo "I have a $color $car"; // I have a red BMW?></body></html>