PHP Includes & Requires

The include() function allows you to insert one file's contents into another file when that other file is executed.

In English, this means that if you want something like a header, footer, navigation, block of PHP code, etc. to appear on multiple pages of your website, there is a solution that does not involve typing it in every time. By putting this information into separate files and including those files whenever necessary, you can save on time, space and clutter by updating only a single file.

This function includes files with extensions such as .inc, .html, .php & .txt as needed. It includes data such as HTML markup, PHP code, and/or text. The best part is that if the included file contains PHP code, that PHP code can be used in (referenced by) the file that is doing the including.

(Example: If $variable is set in page1.php and page1.php is included in page2.php, then $variable can be used in page2.php below where the include() function includes page1.php.)

The include() function syntax is: include("path to file + name of file + file extension");


If the file cannot be found, or cannot be opened, etc. an error will be spit out on the page, and the remainder of the page will be executed normally.

The require() function is identical to the include() function, with the exception that, if the file cannot be found or the page cannot be opened, the require() function considers the error to be fatal and stops executing the remainder of the file. For this reason, require() is recommended instead of include(), because scripts should not continue after an error.

The include_once() and require_once() functions perform exactly the same as include() and require(), with the exception that, as their name implies, if the code from their files has already been included in the file, they will not be included again.

Guess what? You can name your included files anything you want, because your visitors will never see your included files, or even know that they exist!

I should probably mention that the include() and require() "functions" are not really functions, and that they are "language constructs" like the echo "function", but who cares, right?!