Testing if a PHP include file was included

Posted in PHP -

PHP's include() and include_once() functions can return values to the calling script which can be useful for testing to see if the file was actually included, for example if a configuration file whose filename is based on the website's domain name was included. If no return value is set then it will return integer 1 if included, or boolean false if not.

Code example

So you could do this, for example:

if(!@include_once('/path/to/some-script.php')) {
  // do something

The @ symbol suppresses warnings from being displayed if error reporting permits errors of E_WARNING to be reported and display_errors is on.

Using return

The included file can return a value to the calling script, for example like so:

return 1;

Just like in a function call, execution will return from the include file to the calling script at the point return is called, so no further code in the file will be executed.

If you returned 0 from the include file, then in the first example the code in the curly braces would be executed.

As noted in the opening paragraph, if no return value is set in an include file then it will default to integer 1 after the code executes or boolen false if the file could not be included.

require() and require_once()

Returning values works the same way for require() and require_once() as it does for include() and include_once(), also defaulting to integer 1 if not set.

However, a fatal error is issued if a file cannot be required so you can't test for it being required in your code.

Related posts: