Using PHP include statement we can import all of the code, text, or markup from another file to the file where we write this statement.
When we create a project where we would need multiple PHP scripts, including files it becomes necessary.
require is another statement that works the same way as PHP include.
As I mentioned that both
include will works the same way, the only difference between both of them is what it would display in case of failure.
In the case of ‘require’ it would produce a fatal error (E__COMPILE_ERROR) and the execution of the script will stop.
On other hand ‘include’ will only produce a warning and execution will not stop.
Here is the syntax for include and require:
#Syntax for inlude: include 'filename'; #Syntax for require: require 'filename';
How to Use Include in PHP
In CMS, Take WordPress, for example, we create multiple files for the different sections of the webpage.
We create different files for the Header, Sidebar, and Footer.
and using statements like include we can easily join those different pages.
It would save time and we don’t need to write the same code again and again.
Here is take these codes for example:
<html> <body> <h1>Welcome to my website page!</h1> <p>Some text.</p> <p>Some more text.</p> </body> </html>
Assume this is the main part and we created another file named “footer.php” for the footer section.
<?php echo "<p>Copyright" . date("Y") . " By Rahul Bodana</p>"; ?>
We would include that file this way:
<html> <body> <h1>Welcome to my home page!</h1> <p>Some text.</p> <p>Some more text.</p> <?php include 'footer.php';?> </body> </html>
Require Vs Include: which one to use when?
As mentioned earlier the only difference is what it will do when it encountered an error.
So basically it comes to this, If the file that we included is absolutely necessary and we don’t want to run our script without it we would use
But if the script must continue even if there is an error in running included files, we should use