PHP - File Inclusion

    PHP - File Inclusion

    PHP supports the use of two functions that allows you to put the content of one PHP file to another PHP file. After the inclusion, the file get executes by the server. The two functions are:

    • include() function
    • require() function

    Using this feature of PHP you can easily use different functions, headers or elements that you can include on various pages to minimize the effort od coding and to make website changes easily. Instead of changing thousands of code you can just make a change to a single file and include them in the appropriate file.

    1. include() function

    With the help of include() function, you can copy the complete content of one PHP file into the required file. This function will throw an error if there is any kind of problem that occurs during copying the content but the file keeps on executing.

    Example 1. Creating one file (first-demo.php)

    <a href="http://www.helloworld.com/index.htm">Home</a> - 
    <a href="http://www.helloworld.com/ebxml">ebXML</a> - 
    <a href="http://www.helloworld.com/ajax">AJAX</a> - 
    <a href="http://www.helloworld.com/perl">PERL</a> <br />

    2. Creating a second file(second_demo.php)

    <html>
       <body>   
          <?php include("first_demo.php"); ?>
          //Including PHP file      
       </body>
    </html>

    2. require() function

    require() function will copy the content of one file to another file. Unlike include() function, require() function generates an error if there is any problem in loading one PHP file content to the other file but instead of keep on executing the file it halts the execution. Both functions work almost the same except they handle the errors in a different way.

    Example

    <html>
       <body>
          <?php require("axfirst_demo.php"); ?>
    Echo “wrong file”;
          //Including PHP file      
       </body>
    </html>

    There will be no output is generated as we have passed the wrong file name and require() function will halt the execution. But in case of include() function the “wrong file” will get executed.

    People are also reading: