In this tutorial, we will learn about include and require in PHP. Include and Required both are used to copy text/code/markup from the specified file into the file where the copy or require statement is used.
Include and require in PHP makes it so simple to manage such kind of code which we need in multiple files for example code for the navigation bar and footer(because we need same navigation bar and footer in multiple pages).
Before diving deep it is important to know what is different between these two statements(include and require)
Difference between include and require:
We know both include and require used to copy content from one file into another but they both works differently only in the case upon failure(file not found):
- require will show a fatal error (E_COMPILE_ERROR) and stop the script from executing
- include will only show a warning (E_WARNING) and the script will continue to execute
Syntax of require and include:
include 'filename'; or require 'filename';
PHP include example program:
First of all we will create a file which we want to include. Suppose we have saved this file as hello.php.
<?php echo "<h2>Hello, Welcome to Owlbuddy.</h2>"; ?>
Now we will write code of another file where we want to include hello.php.
<html> <body> <?php include 'hello.php';?> </body> </html>