I see php CMS using include instead of require for their important files. SHouldn't this files such as header.php be required? THe script continues if the file is unable to be opened!
Either the author didn't know the difference between include and require or he doesn't mind if the file doesn't get included.
The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.
Depends. Could be the sign of laziness or uneducated developer. But if the header is an important file—i.e. contains authorization logic (which it shouldn't)—then yes, you would want to use require
in place of include
.
include allows for a warning to occur, so the rest of the script will still execute. require causes a fatal error to occur, which stops execution immediately. This typically results in a completely blank page with the error description outputted. In my opinion, require_once is the most convenient, especially if you have a script within a script within a script, because a fatal error is outputted if you define functions multiple times. I personally prefer, require_once() because it prevents the php code from spilling into HTML for the user to see
Here are a few examples
Condition: file test.php does not exist
Using include() :
<?php include("test.php"); print "<p>Hey This String Still Prints Dude!</p>"; ?>
Result:
Warning: include(test.php) [function.include]: failed to open stream: No such file or directory in /home/webspotm/public_html/error/index.php on line 2 Warning: include() [function.include]: Failed opening 'test.php' for inclusion (include_path='.:/home/webspotm/.imports') in /home/webspotm/public_html/error/index.php on line 2 Hey This String Still Prints Dude!
Using require() :
<?php require("test.php"); print "<p>Yea don't even try, this code ain't gonna show!</p>"; ?>
Result:
Warning: require(test.php) [function.require]: failed to open stream: No such file or directory in /home/webspotm/public_html/error/index.php on line 2 Fatal error: require() [function.require]: Failed opening required 'test.php' (include_path='.:/home/webspotm/.imports') in /home/webspotm/public_html/error/index.php on line 2