Saturday, August 4, 2012

The difference between PHP "include" and "require" statements?

Although I have been developing in PHP for years I did not realize what the difference between "require" and "include" statements were.  You see them used often and seem to be interchangeable. There is, however, one main difference. Include and require are identical, except upon failure:
  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script
  • include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is missing, use include. Otherwise, always use require to help avoid compromising your application's security and integrity.

Of course, I recommend to use the require_once and include_once statements when including code that may be loaded by multiple files.  This will prevent trying to load the same file twice.

No comments:

Post a Comment