This page provides a quick introduction to Guzzle and introductory examples.If you have not already installed, Guzzle, head over to theInstallationpage.
You can send requests with Guzzle using aGuzzleHttp\ClientInterfaceobject.
useGuzzleHttp\Client;$client=newClient([// Base URI is used with relative requests'base_uri'=>'http://httpbin.org',// You can set any number of default request options.'timeout'=>2.0,]);
Clients are immutable in Guzzle, which means that you cannot change the defaults used by a client after it's created.
The client constructor accepts an associative array of options:
base_uri(string|UriInterface) Base URI of the client that is merged into relativeURIs. Can be a string or instance of UriInterface. When a relative URIis provided to a client, the client will combine the base URI with therelative URI using the rules described inRFC 3986, section 5.2.
// Create a client with a base URI$client=newGuzzleHttp\Client(['base_uri'=>'https://foo.com/api/']);// Send a request to https://foo.com/api/test$response=$client->request('GET','test');// Send a request to https://foo.com/root$response=$client->request('GET','/root');
Don't feel like reading RFC 3986? Here are some quick examples on how abase_uri is resolved with another 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 |
handlerPsr7\Http\Message\RequestInterface and arrayof transfer options, and must return aGuzzleHttp\Promise\PromiseInterface that is fulfilled with aPsr7\Http\Message\ResponseInterface on success....Magic methods on the client make it easy to send synchronous requests:
$response=$client->get('http://httpbin.org/get');$response=$client->delete('http://httpbin.org/delete');$response=$client->head('http://httpbin.org/get');$response=$client->options('http://httpbin.org/get');$response=$client->patch('http://httpbin.org/patch');$response=$client->post('http://httpbin.org/post');$response=$client->put('http://httpbin.org/put');
You can create a request and then send the request with the client when you'reready:
useGuzzleHttp\Psr7\Request;$request=newRequest('PUT','http://httpbin.org/put');$response=$client->send($request,['timeout'=>2]);
Client objects provide a great deal of flexibility in how request aretransferred including default request options, default handler stack middlewarethat are used by each request, and a base URI that allows you to send requestswith relative URIs.
You can find out more about client middleware in theHandlers and Middleware page of the documentation.
You can send asynchronous requests using the magic methods provided by a client:
$promise=$client->getAsync('http://httpbin.org/get');$promise=$client->deleteAsync('http://httpbin.org/delete');$promise=$client->headAsync('http://httpbin.org/get');$promise=$client->optionsAsync('http://httpbin.org/get');$promise=$client->patchAsync('http://httpbin.org/patch');$promise=$client->postAsync('http://httpbin.org/post');$promise=$client->putAsync('http://httpbin.org/put');
You can also use thesendAsync() andrequestAsync() methods of a client:
useGuzzleHttp\Psr7\Request;// Create a PSR-7 request object to send$headers=['X-Foo'=>'Bar'];$body='Hello!';$request=newRequest('HEAD','http://httpbin.org/head',$headers,$body);$promise=$client->sendAsync($request);// Or, if you don't need to pass in a request instance:$promise=$client->requestAsync('GET','http://httpbin.org/get');
The promise returned by these methods implements thePromises/A+ spec, provided by theGuzzle promises library. This meansthat you can chainthen() calls off of the promise. These then calls areeither fulfilled with a successfulPsr\Http\Message\ResponseInterface orrejected with an exception.
usePsr\Http\Message\ResponseInterface;useGuzzleHttp\Exception\RequestException;$promise=$client->requestAsync('GET','http://httpbin.org/get');$promise->then(function(ResponseInterface$res){echo$res->getStatusCode()."\n";},function(RequestException$e){echo$e->getMessage()."\n";echo$e->getRequest()->getMethod();});
You can send multiple requests concurrently using promises and asynchronousrequests.
useGuzzleHttp\Client;useGuzzleHttp\Promise;$client=newClient(['base_uri'=>'http://httpbin.org/']);// Initiate each request but do not block$promises=['image'=>$client->getAsync('/image'),'png'=>$client->getAsync('/image/png'),'jpeg'=>$client->getAsync('/image/jpeg'),'webp'=>$client->getAsync('/image/webp')];// Wait for the requests to complete; throws a ConnectException// if any of the requests fail$responses=Promise\Utils::unwrap($promises);// You can access each response using the key of the promiseecho$responses['image']->getHeader('Content-Length')[0];echo$responses['png']->getHeader('Content-Length')[0];// Wait for the requests to complete, even if some of them fail$responses=Promise\Utils::settle($promises)->wait();// Values returned above are wrapped in an array with 2 keys: "state" (either fulfilled or rejected) and "value" (contains the response)echo$responses['image']['state'];// returns "fulfilled"echo$responses['image']['value']->getHeader('Content-Length')[0];echo$responses['png']['value']->getHeader('Content-Length')[0];
You can use theGuzzleHttp\Pool object when you have an indeterminateamount of requests you wish to send.
useGuzzleHttp\Client;useGuzzleHttp\Exception\RequestException;useGuzzleHttp\Pool;useGuzzleHttp\Psr7\Request;useGuzzleHttp\Psr7\Response;$client=newClient();$requests=function($total){$uri='http://127.0.0.1:8126/guzzle-server/perf';for($i=0;$i<$total;$i++){yieldnewRequest('GET',$uri);}};$pool=newPool($client,$requests(100),['concurrency'=>5,'fulfilled'=>function(Response$response,$index){// this is delivered each successful response},'rejected'=>function(RequestException$reason,$index){// this is delivered each failed request},]);// Initiate the transfers and create a promise$promise=$pool->promise();// Force the pool of requests to complete.$promise->wait();
Or using a closure that will return a promise once the pool calls the closure.
$client=newClient();$requests=function($total)use($client){$uri='http://127.0.0.1:8126/guzzle-server/perf';for($i=0;$i<$total;$i++){yieldfunction()use($client,$uri){return$client->getAsync($uri);};}};$pool=newPool($client,$requests(100));
In the previous examples, we retrieved a$response variable or we weredelivered a response from a promise. The response object implements a PSR-7response,Psr\Http\Message\ResponseInterface, and contains lots ofhelpful information.
You can get the status code and reason phrase of the response:
$code=$response->getStatusCode();// 200$reason=$response->getReasonPhrase();// OK
You can retrieve headers from the response:
// Check if a header exists.if($response->hasHeader('Content-Length')){echo"It exists";}// Get a header from the response.echo$response->getHeader('Content-Length')[0];// Get all of the response headers.foreach($response->getHeaders()as$name=>$values){echo$name.': '.implode(', ',$values)."\r\n";}
The body of a response can be retrieved using thegetBody method. The bodycan be used as a string, cast to a string, or used as a stream like object.
$body=$response->getBody();// Implicitly cast the body to a string and echo itecho$body;// Explicitly cast the body to a string$stringBody=(string)$body;// Read 10 bytes from the body$tenBytes=$body->read(10);// Read the remaining contents of the body as a string$remainingBytes=$body->getContents();
You can provide query string parameters with a request in several ways.
You can set query string parameters in the request's URI:
$response=$client->request('GET','http://httpbin.org?foo=bar');
You can specify the query string parameters using thequery requestoption as an array.
$client->request('GET','http://httpbin.org',['query'=>['foo'=>'bar']]);
Providing the option as an array will use PHP'shttp_build_query functionto format the query string.
And finally, you can provide thequery request option as a string.
$client->request('GET','http://httpbin.org',['query'=>'foo=bar']);
Guzzle provides several methods for uploading data.
You can send requests that contain a stream of data by passing a string,resource returned fromfopen, or an instance of aPsr\Http\Message\StreamInterface to thebody request option.
useGuzzleHttp\Psr7;// Provide the body as a string.$r=$client->request('POST','http://httpbin.org/post',['body'=>'raw data']);// Provide an fopen resource.$body=Psr7\Utils::tryFopen('/path/to/file','r');$r=$client->request('POST','http://httpbin.org/post',['body'=>$body]);// Use the Utils::streamFor method to create a PSR-7 stream.$body=Psr7\Utils::streamFor('hello!');$r=$client->request('POST','http://httpbin.org/post',['body'=>$body]);
An easy way to upload JSON data and set the appropriate header is using thejson request option:
$r=$client->request('PUT','http://httpbin.org/put',['json'=>['foo'=>'bar']]);
In addition to specifying the raw data of a request using thebody requestoption, Guzzle provides helpful abstractions over sending POST data.
Sendingapplication/x-www-form-urlencoded POST requests requires that youspecify the POST fields as an array in theform_params request options.
$response=$client->request('POST','http://httpbin.org/post',['form_params'=>['field_name'=>'abc','other_field'=>'123','nested_field'=>['nested'=>'hello']]]);
You can send files along with a form (multipart/form-data POST requests),using themultipart request option.multipart accepts an array ofassociative arrays, where each associative array contains the following keys:
Psr\Http\Message\StreamInterface to streamthe contents from a PSR-7 stream.useGuzzleHttp\Psr7;$response=$client->request('POST','http://httpbin.org/post',['multipart'=>[['name'=>'field_name','contents'=>'abc'],['name'=>'file_name','contents'=>Psr7\Utils::tryFopen('/path/to/file','r')],['name'=>'other_file','contents'=>'hello','filename'=>'filename.txt','headers'=>['X-Foo'=>'this is an extra header to include']]]]);
Guzzle can maintain a cookie session for you if instructed using thecookies request option. When sending a request, thecookies optionmust be set to an instance ofGuzzleHttp\Cookie\CookieJarInterface.
// Use a specific cookie jar$jar=new\GuzzleHttp\Cookie\CookieJar;$r=$client->request('GET','http://httpbin.org/cookies',['cookies'=>$jar]);
You can setcookies totrue in a client constructor if you would liketo use a shared cookie jar for all requests.
// Use a shared client cookie jar$client=new\GuzzleHttp\Client(['cookies'=>true]);$r=$client->request('GET','http://httpbin.org/cookies');
Different implementations exist for theGuzzleHttp\Cookie\CookieJarInterface:
GuzzleHttp\Cookie\CookieJar class stores cookies as an array.GuzzleHttp\Cookie\FileCookieJar class persists non-session cookiesusing a JSON formatted file.GuzzleHttp\Cookie\SessionCookieJar class persists cookies in theclient session.You can manually set cookies into a cookie jar with the named constructorfromArray(array$cookies,$domain).
$jar=\GuzzleHttp\Cookie\CookieJar::fromArray(['some_cookie'=>'foo','other_cookie'=>'barbaz1234'],'example.org');
You can get a cookie by its name with thegetCookieByName($name) methodwhich returns aGuzzleHttp\Cookie\SetCookie instance.
$cookie=$jar->getCookieByName('some_cookie');$cookie->getValue();// 'foo'$cookie->getDomain();// 'example.org'$cookie->getExpires();// expiration date as a Unix timestamp
The cookies can be also fetched into an array thanks to thetoArray() method.TheGuzzleHttp\Cookie\CookieJarInterface interface extendsTraversable so it can be iterated in a foreach loop.
Guzzle will automatically follow redirects unless you tell it not to. You cancustomize the redirect behavior using theallow_redirects request option.
true to enable normal redirects with a maximum number of 5redirects. This is the default setting.false to disable redirects.$response=$client->request('GET','http://github.com');echo$response->getStatusCode();// 200
The following example shows that redirects can be disabled.
$response=$client->request('GET','http://github.com',['allow_redirects'=>false]);echo$response->getStatusCode();// 301
Tree View
The following tree view describes how the Guzzle Exceptions dependon each other.
. \RuntimeException└── TransferException (implements GuzzleException) ├── ConnectException (implements NetworkExceptionInterface) └── RequestException ├── BadResponseException │ ├── ServerException │ └── ClientException └── TooManyRedirectsException
Guzzle throws exceptions for errors that occur during a transfer.
AGuzzleHttp\Exception\ConnectException exception is thrown in theevent of a networking error. This exception extends fromGuzzleHttp\Exception\TransferException.
AGuzzleHttp\Exception\ClientException is thrown for 400level errors if thehttp_errors request option is set to true. Thisexception extends fromGuzzleHttp\Exception\BadResponseException andGuzzleHttp\Exception\BadResponseException extends fromGuzzleHttp\Exception\RequestException.
useGuzzleHttp\Psr7;useGuzzleHttp\Exception\ClientException;try{$client->request('GET','https://github.com/_abc_123_404');}catch(ClientException$e){echoPsr7\Message::toString($e->getRequest());echoPsr7\Message::toString($e->getResponse());}
AGuzzleHttp\Exception\ServerException is thrown for 500 levelerrors if thehttp_errors request option is set to true. Thisexception extends fromGuzzleHttp\Exception\BadResponseException.
AGuzzleHttp\Exception\TooManyRedirectsException is thrown when toomany redirects are followed. This exception extends fromGuzzleHttp\Exception\RequestException.
All of the above exceptions extend fromGuzzleHttp\Exception\TransferException.
Guzzle exposes a few environment variables that can be used to customize thebehavior of the library.
GUZZLE_CURL_SELECT_TIMEOUTcurl_multi_select(). Some systemshave issues with PHP's implementation ofcurl_multi_select() wherecalling this function always results in waiting for the maximum duration ofthe timeout.HTTP_PROXYDefines the proxy to use when sending requests using the "http" protocol.
Note: because the HTTP_PROXY variable may contain arbitrary user input on some (CGI) environments, the variable is only used on the CLI SAPI. Seehttps://httpoxy.org for more information.
HTTPS_PROXYNO_PROXYGuzzle can utilize PHP ini settings when configuring clients.
openssl.cafile