[php: guzzle] Guzzle, an extensible PHP HTTP client. #php
PHP 製の有名な HTTP クライアント。非同期のリクエスト送信や PSR-7 準拠の実装にも対応していたりとモダンでイイ感じ。
php.ini
で allow_url_fopen=enable
を指定$ composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
// Init
$client = new Client([
'base_uri' => 'http://example.com/api',
'timeout' => 2.0, // sec
]);
// Sync request.
$response = $client->get('test'); // GET http://example.com/api/test
$response = $client->post('/root'); // POST http://example.com/root
// Querystring.
$client->get($url, [
'query' => ['foo' => 'bar']
]);
// POST params.
$r = $client->put($url, [
'json' => ['foo' => 'bar']
]);
$response = $client->post($url, [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
// POST multipart/form-data
$response = $client->post($url, [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'other_file',
'contents' => 'hello',
'filename' => 'filename.txt',
'headers' => [
'X-Foo' => 'this is an extra header to include'
]
]
]
]);
base_uri
と各リクエストの URI は末尾 /
含め厳格にルールが分かれているので注意。
base_uri | URI | Result |
---|---|---|
http://foo.com | /bar | http://foo.com/bar |
http://foo.com/foo | /bar | http://foo.com/bar |
http://foo.com/foo | bar | http://foo.com/bar |
http://foo.com/foo/ | bar | http://foo.com/foo/bar |
http://foo.com | http://baz.com | http://baz.com |
http://foo.com/?bar | bar | http://foo.com/bar |
$promise = $client->getAsync('http://httpbin.org/get');
$promise->then(
function (\Psr\Http\Message\ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (\GuzzleHttp\Exception\RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
$client->get('/', [
'http_errors' => trye, // Throws exception on 4xx ~ 5xx.
'verify' => true, // Throws exception on invalid certs.
'debug' => false, // Print logs to stdout.
'headers' => [
'Content-Type: application/json',
],
'config' => [ // @see http://bit.ly/2MDjnQY
'curl' => [
'CURLOPT_NOBODY' => true,
],
],
'sink' => '/path/to', // Specify path the response will be saved.
]);