PHP Include

PHP Include


PHP allows us to create various elements and functions, which are used several times in many pages. It takes much time to script these functions in multiple pages. Therefore, use the concept of file inclusion that helps to include files in various programs and saves the effort of writing code multiple times.

"PHP allows you to include file so that a page content can be reused many times. It is very helpful to include files when you want to apply the same HTML or PHP code to multiple pages of a website." There are two ways to include file in PHP.

  1. include
  2. require

Include():If a.php is a php script calling b.php with include() statement, and does not find b.php, a.php executes with a warning, excluding the part of the code written within b.php

Syntax:

       include 'filename'; or include ('filename')
             and 
       require 'filename'; or require ('filename')

Let understand with example ,There are two php files ( my_inlclude.php ) and (myfile.php)

File1 : my_include.php:

<?php

$sports1 = "football";

$sports2 = "cricket";

?>

File2 : File myfile.php, which includes my_include.php :

<?php

include('my_include.php');

echo "I prefer&nbsp;". $sports1 ."&nbsp; than&nbsp;". $sports2;

?>

 

Output :

require (): The require statement is also used to include a file into the PHP code.. On failure it produce a fatal E_ERROR level error.

For Example :

The welcome.php file is not available in the same directory, which we have included. So, it will produce a warning about that missing file but also display the output.

<?php  

    echo "HELLO";  

    //require welcome.php file  

    require("welcome.php");  

    echo "The welcome file is required.";  

?>  

Output :