Require File

☰ Menu Content


The require function is used just like?include function of the previous lesson.

But there is one big difference between the two functions.

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("menu.inc");
echo "Hello World!";
?>
Display:
Warning: main(menu.inc):
failed to open stream: No such file or directory in
/home/websiteName/FolderName/menu.inc on line 2
Warning: main(): Failed opening 'menu.inc'
for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/websiteName/FolderName/menu.inc on line 2
Hello World!

Notice that our echo statement was executed

With the require function we would get something like the following example.

PHP Code:
<?php require("menu.inc");
echo "Hello World!";
?>
Display:
Warning: main(menu.inc):
failed to open stream: No such file or directory in
/home/websiteName/FolderName/menu.inc on line 2
Fatal error: main(): Failed opening required
'menu.inc'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/websiteName/FolderName/menu.inc on line 2

Notice that the echo statement was not executed.

That was because our script execution died after the require function returned a fatal error!?

Require function should be used instead of include function because your scripts should not be executing if necessary files are missing or misnamed.

Note
For more detail please see Php Manual at http://www.php.net

Php Tutorial Content (menu)