What is the difference between include, include_once, require, and require_once

Started by samuel88, May 16, 2025, 02:43:16 PM

Previous topic - Next topic

samuel88

I'm currently learning PHP and I came across four different statements used to include files: include, include_once, require, and require_once.

I understand they are all used to bring in external PHP files, but I'm a bit confused about the actual differences between them — especially how they handle errors and when it's appropriate to use one over the other.

Could someone please explain the key differences between these statements and provide some examples or common use cases for each? Also, are there any best practices to follow when deciding which one to use?

 
Thanks in advance!




daber88

Here's a one-line explanation for each:

  • include: Includes a file and continues execution even if the file is missing.
  • require: Includes a file but stops execution if the file is missing.
  • include_once: Includes a file only once and continues execution if the file is missing.
  • require_once: Includes a file only once and stops execution if the file is missing.


hxxp:flatcoding.com/tutorials/php/php-file-inclusion-require-include-require_once-include_once/ [nonactive]


GL700Wing

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
Life doesn't have to be perfect to be wonderful ...

Slava
Ukraini!
"Before you allow people access to your forum, especially in an administrative position, you must be aware that that person can seriously damage your forum. Therefore, you should only allow people that you trust, implicitly, to have such access." -Douglas

Advertisement: