Include Files – PHP Advanced
In PHP: before the server executes, it is possible to insert files of one PHP file into another PHP file with help of include or require statement.
Include and Require statements are identical, except upon failure:
Only warning is produced by include (E_WARNING) and script will continue.
Fatal error will be produced by require (E_COMPILE_ERROR) and stop the script.
Including files saves lots of work. You can create header, footer or any other web files for your web pages and when header/footer needs to be updated, You can simply update header include file.
include ‘filename,php’;
require ‘filename.php’; //both are the syntax
Include :
At first, i have created two files for Navigation bar and Footer.
Navigation Bar ( nav.php )
<?php
echo ‘<a href=”#home”>Home</a>
<a href=”#projects”>Projects</a>
<a href=”#tutorial”>Tutorials</a>
<a href=”#language”>Languages</a> ‘;
?>
<style>
a{
font-style: italic;
background-color: #333;
color:white;
padding:8px 18px;
text-decoration: none;
}
</style>
Footer ( footer.php )
<?php
echo “<p>Copyright ©” . date(“Y”) . ” <b> code-projects.org </b> </p>”;
?>
AND NOW I HAVE INCLUDED THESE TWO FILES ( footer.php ) AND ( nav.php ) IN A SINGLE WEB PAGE
<!DOCTYPE html> <html> <body> <?php include 'nav.php';?> </div> <h1>Welcome To Code Projects!</h1> <p> <b> <i>Projects, Tutorials and More. . </b> </i> </p> <?php include 'footer.php';?> </body> </html>
Output :
Require :
To include a file into the PHP code, require statement is also used. Between ‘include’ and ‘require’ there’s one big difference.
The script will continue performing when file is included with include statement and PHP cannot find it.
<!DOCTYPE html> <html> <body> <h1>Welcome To Code Projects!</h1> <?php require 'requireexample.php'; echo "Projects, $color and $car."; ?> </body> </html>
Output:
Here echo statement won’t Run, script execution dies after the require statement returned a fatal error