Page 1 of 1
include error trapping - help!
Posted: Wed Jul 07, 2004 7:13 pm
by crabyars
I'm working on a small script, it needs to include a file (which should already be in the include path)
I would like to trap include errors, so that if the file can't be found I can display a message like "cannot find xxx.php"
I tried file_exists, but that doesn't seem to search through the include path.
thanks!
Posted: Wed Jul 07, 2004 7:27 pm
by feyd
try using [php_man]fopen[/php_man] if you want to search the include path.
Posted: Wed Jul 07, 2004 7:39 pm
by crabyars
Thanks feyd,
that proved to be a wee bit tricky, I've found a clean solution (I think) and so I'll post it here:
Code: Select all
$includefile = "foo.php";
if ( !@include($includefile) ) {
echo "ERROR: $includefile not found in include path!";
}
This seems to work fine, handy for simple error feedback.
Posted: Wed Jul 07, 2004 8:02 pm
by redmonkey
crabyars wrote:Thanks feyd,
that proved to be a wee bit tricky, I've found a clean solution (I think) and so I'll post it here:
Code: Select all
$includefile = "foo.php";
if ( !@include($includefile) ) {
echo "ERROR: $includefile not found in include path!";
}
This seems to work fine, handy for simple error feedback.
This method doesn't actually work too well! The @ infront of the include not only supresses errors generated by the actual include function but it also supresses errors within the included file (even fatal errors which surprised me).
Example....
include.php
Code: Select all
<?php
if (!@include('fatal_error.php'))
{
echo 'Failed to include fatal_error.php';
}
?>
fatal_error.php
Code: Select all
<?php
trigger_error('I''m a fatal error', E_USER_ERROR);
?>
Running fatal_error.php on it's own produces a fatal error (no surprise there). However, running include.php results in a blank page! (this is the case with PHP4.3.7 not sure about others)
Posted: Wed Jul 07, 2004 9:16 pm
by crabyars
Hey, thanks for the note. I want to try and get it right.
I tried your examples, but I don't get any error messages when I run fatal_error.php alone. I'm on PHP Version 4.3.4, perhaps my error reporting is at a diff level than yours.. hmmm
Do you have any other suggestions to do what I'm trying to accomplish? Perhaps I need to go Feyd's route after all..
Posted: Wed Jul 07, 2004 9:29 pm
by crabyars
Ok, this seems to work as well, from Feyd's initial suggestion
Code: Select all
$includefile="foo.php";
$handle = fopen($includefile, "r", 1);
if ($handle) {
fclose($handle);
include ($includefile);
} else {
echo "file: $includefile not found in path";
echo "handle is: $handle";
}
any comments?