PHP Require Function
Just like the previous lesson, the require function is used to include
a file into your PHP code. However there is one huge difference between
the two functions, though it might not seem that big of a deal.
Require vs Include
When you include a file with the include function 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 function
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.
Download Tizag.com's PHP Book
If you would rather download the PDF of this tutorial, check out our
PHP eBook from the Tizag.com store.
Print it out, write all over it, post your favorite lessons all over your wall! |