PHP Tutorial


PHP 7 Include And Require


PHP Include and Require Functions

PHP provides many built-in functions and allows us to create different functions and elements used multiple times across multiple pages, but sometimes it is difficult to code the same function on multiple pages which takes a lot of time. If we use the concept of file inclusion, according to which we can use the same code or function on multiple pages, which takes less time and we want to change or edit the code or function, then we need to change or edit only one source file.

Also, we will explain the difference between include and require in PHP with example.

There are two methods to include files in PHP.

  • PHP include() function
  • PHP require() function

PHP include() function

The PHP include () function is used to include other files in the PHP code. This function executes code or function contained in another file.

Note: If the included file is not found. In this case, it does not prevent the whole PHP script from being executed, but in this case, this warning message about missing files appears.

Syntax:

    include 'filename';

Example: Explain concept of file inclusion with PHP include() function.

Let's create two files for include in a PHP file.

The first file name is header.php

    <?php

    <h1> Header </h1>

    ?>

The second file name is footer.php

    <?php
    
    <h3> Footer </h3>

    ?>

Now let's include the given files in a PHP file.

    <!DOCTYPE html>
    <html>
    <body>

    <?php include ' header.php ';?>
    
    <h2> Container </h2> 

    <?php include ' footer.php ';?>

    </body>
    </html>

PHP require() function

PHP require() function also act like PHP include() function. The PHP require () function is used to include other files in the PHP code. This function executes code or function contained in another file.

Note: If the required file is not found. In this case, it does prevent the whole PHP script from being executed.

Syntax:

    require 'filename';

Example: Explain the concept of file inclusion with PHP require() function.

Let's create two files for include in a PHP file. The first file name is header.php

The first file name is header.php

    <?php

    <h1> Header </h1>

    ?>

The second file name is footer.php

    <?php

    <h3> Footer </h3>

    ?>

Now let's include the given files in a PHP file.

    <!DOCTYPE html>
    <html>
    <body>

    <?php require ' header.php ';?>
    
    <h2> Container </h2> 

    <?php require ' footer.php ';?>

    </body>
    </html>

Question :- difference between include and require in php?

Answer: Both of these functions are used to include the file in PHP scripts. But only one of them is different. The require () function stops the entire PHP script. And include () only shows warning messages. But this does not prevent the script from running. When we include the file in the PHP script. No more files are found.