include and require
| include is optional | |
| require is mandatory | |
| The _once variants | |
| Paths: __DIR__ wins |
include is optional
The include statement loads another file, and a missing file raises only a warning while the page keeps running. That makes it right for optional blocks such as sidebars and banners. The full comparison lives at require, require_once, include, include_once.
include(__DIR__ . "/sidebar.php"); echo "page continues";
require is mandatory
The require statement also loads another file, but a missing file stops the page with a fatal error. Use it for code the page cannot work without: configuration, helpers, and database connections.
require(__DIR__ . "/config.php"); echo "page continues";
The _once variants
The include_once and require_once variants load a file at most one time per request. A second request for the same resolved path is skipped, which prevents fatal Cannot redeclare function errors when two files share one helper.
require_once(__DIR__ . "/helpers.php"); require_once(__DIR__ . "/helpers.php"); echo "loaded once";
Paths: __DIR__ wins
Relative paths resolve against the working directory, not against the file holding the statement, so they break when the entry point moves. Prefixing with __DIR__ anchors the path to the current file folder and works from everywhere. For optional modules that may be absent, guard with is_file as shown in the require fallback pattern.
require(__DIR__ . "/lib/db.php");
Next: Namespaces
Article author: Arthur Isaev