Error Handling
Before PHP 5.3.0, an HTTP streams wrapper operation resulting in an HTTP error response (i.e. a 4xx or 5xx status code) causes a PHP-level warning to be emitted. This warning will only contain the HTTP version, the status code, and the status code description. The function calls for such operations generally return false as a result and leave you without a stream resource to check for more information. Here’s an example of how to get what data you can. <?php function error_handler($errno, $errstr, $errfile, $errline, array $errcontext) { // $errstr will contain something like this: // fopen(http://localhost.example/404): failed to open stream: // HTTP request failed! HTTP/1.0 404 Not Found if ($httperr = strstr($errstr, 'HTTP/')) { // $httperr will contain HTTP/1.0 404 Not Found in the case // of the above example, do something useful with that here } } set_error_handler( 'error_handler', E_WARNING); // If the following statement fails, $stream will be assigned false // and error_handler will be called automatically $stream = fopen('http://localhost.example/404', 'r'); // If error_handler() does not terminate the script, control will // be returned here once it completes its execution restore_error_handler(); ?> This situation has been improved somewhat in PHP 5.3 with the addition of the ignore_errors context setting. When this setting is set to true, operations resulting in errors are treated the same way as successful operations. Here’s an example of what that might look like. <?php $context = stream_context_create( array( 'http' => array( 'ignore_errors' => true ) ) ); $stream = fopen('http://localhost.example/404', 'r', false, $context); // $stream will be a stream resource at this point regardless of // the outcome of the operation $body = stream_get_contents($stream); $meta = stream_get_meta_data($stream); // $meta['wrapper_data'][0] will equal something like HTTP/1.0 404 // Not Found at this point, with subsequent array elements being // other headers $response = explode(' ', $meta['wrapper_data'][0], 3); list($version, $status, $description) = $response; switch (substr($status, 0, 1)) { case '4': case '5': $result = false; default: $result = true; } ?> © HTTP Streams Wrapper — Web Scraping >>> Back to TABLE OF CONTENTS <<< | |
Views: 421 | |
Total comments: 0 | |