Open In App

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

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.



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.






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




<?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.




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




<?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”.




<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.




<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


Article Tags :