Tuesday, August 12, 2008

PHP Require

Just like the previous lesson, the require command is used to include a file into your PHP code. However there is one huge difference between the two commands, though it might not seem that big of a deal.


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:



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:



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.

No comments: