PHP provides two common constructs for including files in web pages:
include. They are basically the same with one minor difference.
require throws a fatal error when it fails; whereas,
include only gives a warning. If you need the included file to continue to process the page, you should use
It is important to keep in mind that a PHP tag cannot start in a calling file and continue in an included file. All PHP code in the included file must be nested in PHP tags.
require is not actually a function, but a language construct, so require statements can be written in two ways:
path_to_file can be an absolute or a relative path.
require_once can be used just like
require. The difference is that if the included file has already been included by earlier code, it will not be re-included.
A Note on Security
If included files are under the web root, they can be accessed just as any other file can. If they have an extension such as
inc then the browser may display them as plain text. With other extensions, the browser may attempt to download the file. If the included file is a PHP file and a user navigates to it, the server will try to process the file and may return errors. As a precaution, you may want to place your included files in a directory above or outside of the web root. This will prevent users from accessing the files directly.
The php.ini contains an
include_path directive, which takes a semi-colon delimited list of paths to directories that PHP should look in for included files.
Here is a code sample that demonstrates how to include files using
The configuration file, php.ini, contains settings for automatically prepending and appending files to every PHP script. These settings are
auto_append_file. By default, they contain no values; however, they can be set to point to a files using absolute paths as follows:
; Automatically add files before or after any PHP document.
auto_prepend_file = "c:/inetput/include/runbefore.inc"
auto_append_file = "c:/inetput/include/runafter.inc"
auto_prepend_file directive can be used to include application-wide variables such as database connection strings or common file paths. The
auto_append_file directive can be used for cleaning up code or for outputting debugging information to the browser.
Note that it is not possible to set different auto-prepend and auto-append files for different directories or different scripts.