Online
 
Thursday, 20 November 2008
 
 

Error Suppression | Print |  E-Mail
 

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.

This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Jumbo Coklat
 
Top! Top!