Table of contents
No headings in the article.
Before answering this question i’ll brief you about why we use include() and require() in PHP -
It's use to insert the content of one PHP file into another PHP file before the server executes it.
Now, little more details about include() and require() -
include() - it includes a specified file. it will produce a warning if it fails to find the file and execute the remaining scripts. include() should be used when the file is not required and application flow should continue when the file is not found.
Syntax -
include ‘filename’;
instead of using include() we can use include_once(),
include_once() - it also includes a specified file but if a file has already been included. it will not be included again. it’ll also produce a warning if it fails to find the file and execute the remaining scripts.
syntax -
include_once();
Now let's learn about require()
require() - it also includes a specified file but it will throw a fatal error (E_COMPILE_ERROR) if it fails to find the file and stops the execution.
syntax -
require ‘filename’;
instead of using require() we can use require_once(),
require_once() - it also includes a specified file but if a file has already been included. it will not be included again. it will throw a fatal error (E_COMPILE_ERROR) if it fails to find the file and stops the execution.
syntax -
require_once();
Now, let us see the difference between include() and require() -
Let’s understand the difference through an example-
Assume we have a file called “file1.php” with some variables defined;
<?php
$name="Anand";
?>
but, here we are not gonna include “file1.php” because here we’ll differentiate include() and require() -
<html>
<body>
<h1> Coder Anand Welcomes You..!<h1>
<?php
include 'noFileExixts.php';
echo "$name is a good boy.";
?>
</body>
</html>
Results of above scripts using include() will be-
Coder Anand Welcomes You..!
is a good boy.
If we do the same example using require statement,the echo statement will not be executed because the script execution dies after the require statement returned a fatal error (E_COMPILE_ERROR) -
<html>
<body>
<h1> Coder Anand Welcomes You..!<h1>
<?php
require 'noFileExixts.php';
echo "$name is a good boy.";
?>
</body>
</html>
Results of above scripts using require() will be-
Coder Anand Welcomes You..!
Difference :-
- require will produce a fatal error (E_COMPILE_ERROR) and stop the script execution.
- include will only produce a warning (E_WARNING) and the script will continue.
Note :-
- Use require() when the file is required by the application.
- Use include() when the file is not required and application should continue when file is not found.
Thank You for reading :)
Happy Learning & Coding :)