That works… If you also want to avoid showing the generated warning, you can use ini_set to temporarily turn off display_errors:
Something tlike this:
$display_errors = ini_get('display_errors'); // get the initial value
ini_set('display_errors',0); // turn off error display for this statement
if (!include 'included.php') {
ini_set('display_errors',$display_errors); // reset error displays to its initial value
echo "Sorry! We have technical problems. Please try it later.";
} else {
ini_set('display_errors',$display_errors); // reset error displays to its initial value
}
The documentation for display_errors doesn’t mention it, but that setting turns off warnings, too (IME).
$display_errors returns to its initial value after the script is run, but to be safe, it’s better to reset it immediately, I think.
file_exists() may also be a good one to use, but keep in mind that the include_path should be searched.
The usual thing is in a development environment: display the errors.
On a live site: log the errors.
But really I don’t like it when you have code that you know may cause errors or warnings, it seems wrong.
Again I think it’s a case of knowing what the context of the question is, what problem are you trying to solve?
In a situaltion where you are expecting that a file may not exist, you should be checking with file_exists.
if(file_exists('included.php')){
include 'included.php' ;
}
else{
// Do something else
}
If you find you are doing this a lot it want’s wrapping in a function.
Oh yes I agree with you 100% @SamA74. The use case here is strange to me - an include file which may or may not be there. Never seen that one before! I am curious to know more details, if @joon1 would provide them.
There’s a problem with using file_exists; it doesn’t check your include path. Here’s an example. Suppose my PHP include path is /usr/share/php/ and I do have a file there called b.php. I also have a file called a.php which is located in the same directory as my include.php file, under my Apache document root.
Then suppose I put this code into my include.php file:
Even though b.php exists, file_exists('b.php') returns FALSE because file_exists does not search the php_includes path, which may be a list of multiple directories. If you want to use file_exists, you’ll have to loop over all the directories in the PHPinclude path when searching for it.
This is probably being nitpicky; maybe in @joon1’s case, it’s known that the include file will be found in exactly one place. In my experience, include files are located in multiple different directories.