Page 1 of 1

How can I handle errors with include/require?

Posted: Tue Jul 03, 2007 10:56 am
by toasty2
I'm wanting to provide my own error message if something fails to include/require.

PHP yells at me if I try something like this:

Code: Select all

include 'file.php' or die('error message');

Posted: Tue Jul 03, 2007 11:13 am
by RobertGonzalez
try using file_exists() before the call to include/require.

Posted: Tue Jul 03, 2007 1:25 pm
by toasty2
Ah, a nice time to use the ternary operator :)

Code: Select all

file_exists('file.php') ? require 'file.php' : die('Error Message');

Posted: Tue Jul 03, 2007 2:19 pm
by mabufo
toasty2 wrote:Ah, a nice time to use the ternary operator :)

Code: Select all

file_exists('file.php') ? require 'file.php' : die('Error Message');
I always want to use that, but somehow never end up doing it. Good for you!

Posted: Tue Jul 03, 2007 3:37 pm
by Ambush Commander
Note that file_exists() won't search your include path. You might be better off overloading your error reporter.

Posted: Tue Jul 03, 2007 5:19 pm
by toasty2
I could just add:

Code: Select all

set_include_path('/');

Posted: Tue Jul 03, 2007 5:21 pm
by Ambush Commander
Yes, but that kind of defeats the purpose of an include path, which is to allow multiple paths to have include files.

Posted: Tue Jul 03, 2007 5:27 pm
by toasty2
Alright, then:

Code: Select all

set_include_path(get_include_path().PATH_SEPARATOR.'/');
Better? :P

Posted: Tue Jul 03, 2007 8:11 pm
by msimoes
If your using PHP5, you can always make it a little more "easier" by implemeting exceptions to the application.


Best regards,
Miguel Simões