0

According to php.net:

The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.

However, there's nothing more about possible errors or error handling.

  1. Does it mean that the only reason why include or require may fail is not being able to find the file? There might be any other reasons?

I also found this & this questions about fail handling.

So, considering I want to include another .php file stored on my server following best practices, and I write:

if ( file_exists('myFile.php') ) {
    require_once 'myFile.php';
}
  1. Can I consider this script to be completely "safe"? Will myFile.php always be included if it exists?
Igor Bykov
  • 2,532
  • 3
  • 11
  • 19
  • Usually scripts that are included are really needed: The application won't work without them. So making the inclusion optional seems very weird to me. – KIKO Software Aug 03 '19 at 10:33
  • if the file you include does have PHP error the include will fail – Giacomo M Aug 03 '19 at 10:33
  • @KIKOSoftware That's exactly why I have this question. If the only reason it might fail is absence of file, then it's possible to handle it somehow in the `else` statement & exit. – Igor Bykov Aug 03 '19 at 10:45
  • 2
    That's not what your code says. There's no `else` with an exit. But I get your point. You do realize that `require()` already does exit with an error? That's the behaviour you describe. I think it would be slightly more efficient to use `include()` in an `try ... catch`. See [this answer](https://stackoverflow.com/a/5369619/3986005). It doesn't need the extra `file_exists()` call. – KIKO Software Aug 03 '19 at 10:56

0 Answers0