Simple Request and Response Handling

Here’s a simple example of the HTTP streams wrapper in action.

<?php
$response = file_get_contents('http://localhost.example');
print_r($http_response_header);
?>

There are a few things to note.

There are a few things to note.

  • The allow_url_fopen PHP configuration setting must be enabled for this to work, which it is in most environments.
  • In this example, the file_get_contents function call is equivalent to making a GET request for the specified URL ’http: //localhost. example’.
  • $response will contain the response body after the call to the file_get_contents function completes.
  • $http_ response_header is implicitly populated with the HTTP response status line and headers after the file_get_contents call because it uses the HTTP streams wrapper within the current scope.

While this example does work, it violates a core principle of good coding practices: no unexpected side effects. The origin of$http_response_header is not entirely obvious because PHP populates it implicitly. Additionally, it’s more restrictive because the variable is only populated within the scope containing the call to file_get_contents. Here’s a better way to get access to the same data from the response headers.

<?php
$handle = fopen('http://localhost.example', 'r');
$response = stream_get_contents($handle);
$meta = stream_get_meta_data($handle);
print_r($meta['wrapper_data']);
?>

Let’s step through this.

  • The    resource    $handle is    created    to    read    from the URL
    http://localhost.example.
  • The stream_get_contents function is called to read the remaining data on the stream pointed to by the $handle resource into $response.
  • The stream_get_meta_data function is called to read metadata for the stream pointed to by the $handle resource into $meta.
  • The wrapper_data index of the $meta array outputs the same array as $http_response_header would within the current scope. So long as $handle is accessible within the current scope, stream_get_meta_data() can be called on it. This makes it more flexible than $http_ response_header. 

© HTTP Streams Wrapper — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (30.08.2014)
Views: 497 | Rating: 0.0/0
Total comments: 0
avatar