The difference between the PHP-functions include(), require(), include_once() und require_once()

24.06.2015 | PhilVanB | Programmierung | PHP

The four functions include(), require(), include_once() and require_once() play an important role in webdevelopment with PHP.

All of these four PHP-functions allow the inclusion of files. The difference between the funtions include() and require() is, that, if the file to be included cannot be found, the include() -function will throw a warning and execute the rest of the script , while the require()-funcion will throw a fatal error and stop executing the script.

Difference between including once and subsequently

The functions include_once() and require_once() only include a file once and they don't allow another inclusion in case a file has already been included.

Include as so:


Illustrating examples

Now the question is when to include which function best? When it is really important to include a certain peace of code, e.g. when a login manager has to check if a user is logged in or not, then the require()-function should be used rather than include(). If it is more important that something like a page is displayed, then include() is the way to go.

Some examples for each of the functions:

Example require()

If the inclusion of a script is absolutely necessary for the proper working of an application, e.g. a file containing configuration variables, then use require().

Example require_once()

This function is useful if the inclusion of the code is necessary but subsequent inclusions would throw an error. That goes for scripts with funtions for instance. If such a script would be included more than once an error would be thrown since functions cannot be redeclared.

Example include()

This function can be used if the script should continue despite an inclusion error and if a subsequent inclusion is not of any disadvantage.

Example include_once()

This function is useful in the case of including remote files and not wanting them to be included several times due to an HTTP overhead.

For more information check ou