Reputation: 693
I'm running a PHP script every night using a cron service. Everything it outputs will be printed to an log file for debug prepossess. The file I use will retrieve xml's from a different site using the function 'file_get_contents()'. But the function can return an error which I really don't want to see as I am already showing a custom error.
Quick example of my piece of code:
$buffer = @file_get_contents('http://xx:xx@xx/xml/xx?offset=2') or print('retry in 5 seconds');
if($buffer === false) {
sleep(5);
$buffer = @file_get_contents('http://xx:xx@xx/xml/xx?offset=2') or print('error notice');
}
The problem is the first one will trigger an error and print it'll retry in 5 seconds. How can I correctly suppress the thrown error?
I have an error handler, but I prefer not to catch this error separately.
Edited: My solution wasn't to change the error_reporting, but to catch the error message. If it starts with 'file_get_contents()', no error will be thrown. This is not the best way, but will do the job for me.
Upvotes: 0
Views: 121
Reputation: 7341
You can try inserting this at the start:
error_reporting(0);
Then after the code with the error/warning:
error_reporting(E_ALL ^ E_WARNING);
Upvotes: 2
Reputation: 1124
Okay, never ever use the @-operator.
In PHP you have two options available: either use a custom error handler or use try/catch.
Since file_get_contents doesn't throw an exception, you can only use the first approach.
You can set an error handler like this: http://php.net/set-error-handler and then act correctly (log something or return a custom error code).
If you just want to turn of all errors use error_reporting(0)
or if you just want to turn off a specific category use error_reporting(E_ALL ^ E_WARNING)
(all but warnings) or specifcy them explicitely error_reporting(E_WARNING | E_NOTICE)
(warnings and notices).
I prefer the first approach, since when you just disable it you have no idea of what's going on in your code.
Upvotes: 1