PHP require() Function

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

The require() function is identical to include(), except that it handles errors differently. the require function is used to include a file into your PHP code

If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

    For eg:

    <html>
    <body>
    <?php
    include(“xyz.php”);
    echo “This is your tutor!”;
    ?>
    </body>
    </html>

    Output:

    Warning: include(xyz.php) [function.include]:failed to open stream:No such file or directory in C:\application\website1\sample.php on line 5
    Warning: include() [function.include]:Failed opening ‘xyz.php’ for inclusion(include_path=’.;C:\php5\web’)in C:\application\website1\sample.php on line 5

    This is your tutor!

Notice that the echo statement is executed! This is because a Warning does not stop the script execution.

Now, let’s run the same example with the require() function.

    For eg:

    <html>
    <body>
    <?php
    require(“xyz.php”);
    echo “This is your tutor!”;
    ?>
    </body>
    </html>

    Output:

    Warning: require(xyz.php) [function.require]:failed to open stream:No such file or directory in C:\application\website1\sample.php on line 5
    Fatal error: require() [function.require]:Failed opening required ‘xyz.php’(include_path=’.;C:\php5\web’)in C:\application\website1\sample.php on line 5

The echo statement is not executed, because the script execution stopped after the fatal error.

It is recommended to use the require() function instead of include(), because scripts should not continue after an error.

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.