PHP | File Include – Difference between include, include_once, require and require_once

There are multiple ways to directly include files into a php script. To include files located on your own server you can use include (include_once) or require (require_once). The specified file is directly included in the calling script where the corresponding function is called.

To open files not located on your webserver you may use the URL-functionality of fopen.  But be aware this has to be activated in your php.ini settings to work properly. Additionally there are many security considerations you may attend to. For instance an attacker could get access to the other webserver and may be able to include faulty or aggressive code into your own script and webserver.

include vs. require

include (Manual) and require (Manual) are basically used for the same task with a single difference: If the specified path could not be found the include function will output a warning. The remaining code will process correctly, if no other error occurs like a function dependency from the included file. If the specified path could not be found the require function will output a fatal error. The remaining code will not be processed – the execution is cancelled.

include_once and require_once

include_once (Manual) and require_once (Manual) ensure, that the specified file is embedded only a single time. Multiple calls are simply ignored. That is the only difference to the previously named functions, include and require. Typically you want to use this function where it is not useful to get the file included multiple times.

When to use which function

Lets find some fields of application for the described functions.:

  • include: If  you have to include redundant content like ads.
  • include_once Useful if you want to include content parts, which are not necessary for the output. Examples could be a single sidebar widget or the whole footer of a website.
  • requirerequire_once If you have to include a set of  functions required for the correct execution of your script