5

This is a simple question one hour of Googling do not seem to solve. How do you catch a failed include in PHP? For the following code:

try {
    include_once 'mythical_file';
} catch (Exception $e) {
    exit('Fatal');
}

echo '?';

With mythical_file not existing, I get the output '?'. I know PHP can not catch failed required because it triggers a Warning Error, but here? What is the best way to catch a failed include? For example, the following works:

(include_once 'unicorn') or exit('!');

but it does not trigger an exception so I cannot retrieve file, line and stack context.

fabjoa
  • 51
  • 1
  • 2
  • You may want to look into [register_shutdown_function()](http://php.net/manual/en/function.register-shutdown-function.php) in combination with [error_get_last()](http://php.net/manual/en/function.error-get-last.php). Should be able to retrieve file, line, etc. – billrichards Jun 26 '15 at 00:08

2 Answers2

2

You can use require_once instead of include_once

Gaurav
  • 28,447
  • 8
  • 50
  • 80
  • Well I guess I will have to close the ticket because apparently it works on some of my virtual hosts and others not (using require will trigger a 500 error). Thanks anyway for your help! – fabjoa Apr 02 '11 at 06:56
  • 1
    @fabjoa, @Gaurav - we don't have "tickets" here, so there's nothing closable. – Dori Apr 03 '11 at 06:24
1

include and include_once trigger warning (E_WARNING), require and require_once trigger error (E_COMPILE_ERROR). So you should use require or require_once.

php.net quote:

"require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue. "

Wh1T3h4Ck5
  • 8,399
  • 9
  • 59
  • 79
  • Do not use `_once` unless you absolutely have to because it affects performance a bit. – transilvlad Apr 11 '14 at 18:11
  • @tntu can you explain? It was my understanding that using require or include when the file is already included is a bigger waste of resources than using _once. Thank you! – billrichards Nov 06 '14 at 17:07
  • @billrichards If you write good code you should never encounter the situation where you include the same file twice. The explanation what the difference in performance is is explained here: http://stackoverflow.com/questions/186338/why-is-require-once-so-bad-to-use – transilvlad Nov 07 '14 at 09:39
  • @tntu thanks for the info and the link! someday when i start writing good code, i'll be able to stop using require_once and include_once – billrichards Nov 07 '14 at 17:02