Open In App

How to include content of a PHP file into another PHP file ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage.

There are two ways to do it by using the following PHP functions.

  • PHP include() Function: It will show the warning if the file does not exist and continue rendering the code
  • PHP require() Function: It will show the error if the file does not exist and stop the program.

If you do not want the script to be interrupted and do not want to stop the script then use the include() otherwise use require(). These two ways of including the files into another save a lot of work and make our code more efficient to understand.

Example 1: In this, there is a file called another_file.php which is included in another file called index.php using the include keyword.

index.php




<html>
  
<body>
    <h2>This is the content of index.php file.</h2>    
    <?php 
        include("another_file.php");
    ?>      
</body>
</html>


another_file.php




<?php
  
  echo "<h2>This is the content of another_file.php</h2>";
  echo "<h3>Hello, good to see you </h3>";
?>


Output:

Example 2:  In this, there is a file called another_file.php which is included in another file called index.php using the require keyword.

index.php




<html>
  
<body>
    <h2>This is the content of index.php file.</h2>
      
    <?php 
        require("another_file.php");
    ?>
</body>
  
</html>


another_file.php




<?php
  
  echo "<h2>This is the content of another_file.php</h2>";
  echo "<h3>Hello, good to see you </h3>";
  
?>


Output:

require

Example 3:  In this, we use include but if it is not able to find another file to include then it gives a warning and executes after code i.e. it prints the remaining content of “index.php”.

index.php




<html>
  
<body>
    
    <h2>This is the content of index.php file.</h2>
    <?php 
        include("another_file.php");
    ?>      
    <h2>This is content after including another_file content</h2>
</body>
</html>


Output:

include, not able to find another file

Example 4:  In this, we use require but if it is not able to find another file to include then it gives a fatal error and does not execute after code i.e. it stops the script by giving an error.

index.php




<html>
  
<body>
    <h2>This is the content of index.php file.</h2>
  
    <?php 
        require("another_file.php");
    ?>      
    <h2>This is content after including another_file content</h2>
        
</body>
</html>


Output:

require, does not able to find another file



Last Updated : 03 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads