Sat. Apr 27th, 2024

PHP Require

Require vs Include

When you include a file with the include command and PHP cannot find it you will see an error message like the following:

PHP Code:

<?php
include("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2 Warning: main(): Failed opening ‘noFileExistsHere.php’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/websiteName/FolderName/tizagScript.php on line 2

Hello World!

Notice that our echo statement is still executed, this is because a Warning does not prevent our PHP script from running. On the other hand, if we did the same example but used the require statement we would get something like the following example.

PHP Code:

<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2
Fatal error: main(): Failed opening required ‘noFileExistsHere.php’ (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/websiteName/FolderName/tizagScript.php on line 2

The echo statement was not executed because our script execution died after the require command returned a fatal error! We recommend that you use require instead of include because your scripts should not be executing if necessary files are missing or misnamed.

5,099 total views, 1 views today