Error Suppression


Some of the errors you're likely to encounter aren't completely preventable. Consider, for example, the following piece of code:

 $webpage = file_get_contents('http://www.example.com'); 

Under ordinary circumstances, $webpage will be populated with the HTML content of the page located at http://www.example.com; however, it's entirely possible that www.example.com is down or otherwise inaccessible. In such a case, PHP will raise an E_WARNING error and set the value of $webpage to FALSE.

 Warning: file_get_contents(http://www.example.com): failed to open stream:  Connection refused in /home/jdoe/public_html/fetchPage.php on line 1 

On a production site, you most certainly would want to show your users a more friendly "Come back later" type message. We can prevent PHP from displaying this error message in any one of several ways. We can use the error_reporting and/or display_errors directives mentioned previously, or we can prefix the potentially fallible command with the Error Suppression Operator "@".

 $webpage = @file_get_contents('http://www.example.com'); 

In this version, if file_get_contents() is unable to retrieve the data, $webpage will be set to FALSE, but no error will be displayed. Our script may then handle the error gracefully:

 <?php     $webpage = @file_get_contents('http://www.example.com');     if ($webpage === false) {      /* Use a "placeholder" webpage for now */      $webpage = '<html><head><title>Example Dot Com Unavailable</title></head><body>     We were unable to retrieve the webpage for www.example.com, please try again      another time.</body></html>';     } ?> 

NOTE

Fatal errors are always fatal regardless of the use of the error-suppression operator, the value of error_reporting, or the presence of another error handler. When a fatal error is encountered, execution of the currently running script will always terminate.




PHP 5 Unleashed
PHP 5 Unleashed
ISBN: 067232511X
EAN: 2147483647
Year: 2004
Pages: 257

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net