Home

Awesome

httpfetch

Build Status Latest Stable Version

httpfetch provides a simple function fetch to make HTTP requests in small scripts easy and fast.

httpfetch relies heavily on RingPHP for its robust low level HTTP abstraction and for the ability to make asynchronous requests.

Use Cases

Install

Via Composer

$ composer require chh/httpfetch

Usage

use function chh\httpfetch\fetch;

$response = fetch("https://www.example.com");

echo stream_get_contents($response['body']);

The chh\httpfetch Namespace

fetch($url, array $options = [])

Makes a HTTP request to the provided URL. The options follow the RingPHP specification for requests and the returned response follows the RingPHP specification for responses.

All requests are made asynchronously by default, when supported by the handler. This can be turned off by setting the future option to false.

httpfetch implements a few additional options for convenience:

Responses are array-like objects with the following keys:

For example a POST request by using the http_method parameter:

$response = fetch('http://www.example.com', [
    'http_method' => 'POST',
    'body' => 'foo'
]);

var_dump($response['status']);
var_dump(stream_get_contents($response['body']));

Example: Doing an async GET request with the Promise API:

fetch('http://www.example.com')->then(function ($response) {
  // Save the response stream:
  $out = fopen('/tmp/foo.txt', 'w+b');
  stream_copy_to_stream($response['body'], $out);
  fclose($out);
});

Example: Doing an async request with the Future API:

$response = fetch('http://www.example.com');

// Do some other stuff

$response->wait();

echo stream_get_contents($response['body']);

Example: Doing requests in parallel:

$response1 = fetch('http://www.example.com');
$response2 = fetch('http://www.foo.com');

echo $response1['status'], "\n";
echo $response2['status'], "\n";

get(), post(), put(), delete(), head(), options()

Helper methods for common HTTP methods. They all follow the same signature of ($url, array $options = []).

Example:

use chh\httpfetch;

// GET request
$response = httpfetch\get("https://www.example.com");

// POST request with body
$response = httpfetch\post("https://www.example.com", [
    'body' => 'foo',
]);

set_default_handler(callable $handler)

Overrides the Guzzle Ring Client handler which is used by the fetch function. Handlers are callables which follow the Ring specification. Reset the handler to the default by passing null.

Example: Force the usage of PHP's http:// stream wrapper:

chh\httpfetch\set_default_handler(new Guzzle\Ring\Client\StreamHandler);

fetch('http://example.com');

Testing

$ make test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email me@christophh.net instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.