Types of Includes
The include statement is only one of four statements that you can use to include another PHP file in a currently running script. Those four statements are:
- include
- require
- include_once
- require_once
include and require are almost identical. The only difference between them is what happens when the specified file is unable to be included (that is, if it does not exist, or if the web server doesn’t have permission to read it). With include, a warning is displayed[1] and the script continues to run. With require, an error is displayed and the script stops.
In general, therefore, you should use require whenever the main script is unable to work without the script to be included. I do recommend using include whenever possible, however. Even if the db.inc.php file for your site is unable to be loaded, for example, you might still want to let the script for your front page continue to load. None of the content from the database will display, but the user might be able to use the Contact Us link at the bottom of the page to let you know about the problem!
include_once and require_once work just like include and require, respectively — but if the specified file has already been included at least once for the current page request (using any of the four statements described here), the statement will be ignored. This is handy for include files that perform a task that only needs to be done once , like connecting to the database.
Figure 1 shows include_once in action. In the figure, index.php includes two files: categories.inc.php and top10.inc.php. Both of these files use include_once to include db.inc.php, as they both need a database connection in order to do their job. As shown, PHP will ignore the attempt to include db.inc.php in top10.inc.php because the file was already included in categories.inc.php. As a result, only one database connection is created.
Figure 1. Use include_once to avoid opening a second database connection
include_once and require_once are also useful for loading function libraries.
[1] In production environments, warnings and errors are usually disabled in php.ini . In such environments, a failed include has no visible effect (aside from the lack of content that would normally have been generated by the include file); a failed require causes the page to stop at the point of failure. When a failed require occurs before any content is sent to the browser, the unlucky user will see nothing but a blank page!
Types of Includes
by Kevin Yank
















































