Quickstart

This page provides a quick introduction to Guzzle and introductory examples.If you have not already installed, Guzzle, head over to the Installationpage.

Making a Request

You can send requests with Guzzle using a GuzzleHttp\ClientInterfaceobject.

Creating a Client

  1. use GuzzleHttp\Client;
  2.  
  3. $client = new Client([
  4. // Base URI is used with relative requests
  5. 'base_uri' => 'http://httpbin.org',
  6. // You can set any number of default request options.
  7. 'timeout' => 2.0,
  8. ]);

Clients are immutable in Guzzle 6, 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 2.




  1. // Create a client with a base URI
    $client = new GuzzleHttp\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_uriURIResult
http://foo.com/barhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/bar
http://foo.com/foobarhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/foo/bar
http://foo.comhttp://baz.comhttp://baz.com
http://foo.com/?barbarhttp://foo.com/bar

handler
(callable) Function that transfers HTTP requests over the wire. Thefunction is called with a Psr7\Http\Message\RequestInterface and arrayof transfer options, and must return aGuzzleHttp\Promise\PromiseInterface that is fulfilled with aPsr7\Http\Message\ResponseInterface on success. handler is aconstructor only option that cannot be overridden in per/request options.
(mixed) All other options passed to the constructor are used as defaultrequest options with every request created by the client.

Sending Requests

Magic methods on the client make it easy to send synchronous requests:

  1. $response = $client->get('http://httpbin.org/get');
  2. $response = $client->delete('http://httpbin.org/delete');
  3. $response = $client->head('http://httpbin.org/get');
  4. $response = $client->options('http://httpbin.org/get');
  5. $response = $client->patch('http://httpbin.org/patch');
  6. $response = $client->post('http://httpbin.org/post');
  7. $response = $client->put('http://httpbin.org/put');

You can create a request and then send the request with the client when you'reready:

  1. use GuzzleHttp\Psr7\Request;
  2.  
  3. $request = new Request('PUT', 'http://httpbin.org/put');
  4. $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.

Async Requests

You can send asynchronous requests using the magic methods provided by a client:

  1. $promise = $client->getAsync('http://httpbin.org/get');
  2. $promise = $client->deleteAsync('http://httpbin.org/delete');
  3. $promise = $client->headAsync('http://httpbin.org/get');
  4. $promise = $client->optionsAsync('http://httpbin.org/get');
  5. $promise = $client->patchAsync('http://httpbin.org/patch');
  6. $promise = $client->postAsync('http://httpbin.org/post');
  7. $promise = $client->putAsync('http://httpbin.org/put');

You can also use the sendAsync() and requestAsync() methods of a client:

  1. use GuzzleHttp\Psr7\Request;
  2.  
  3. // Create a PSR-7 request object to send
  4. $headers = ['X-Foo' => 'Bar'];
  5. $body = 'Hello!';
  6. $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
  7. $promise = $client->sendAsync($request);
  8.  
  9. // Or, if you don't need to pass in a request instance:
  10. $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 chain then() calls off of the promise. These then calls areeither fulfilled with a successful Psr\Http\Message\ResponseInterface orrejected with an exception.

  1. use Psr\Http\Message\ResponseInterface;
  2. use GuzzleHttp\Exception\RequestException;
  3.  
  4. $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
  5. $promise->then(
  6. function (ResponseInterface $res) {
  7. echo $res->getStatusCode() . "\n";
  8. },
  9. function (RequestException $e) {
  10. echo $e->getMessage() . "\n";
  11. echo $e->getRequest()->getMethod();
  12. }
  13. );

Concurrent requests

You can send multiple requests concurrently using promises and asynchronousrequests.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\Promise;
  3.  
  4. $client = new Client(['base_uri' => 'http://httpbin.org/']);
  5.  
  6. // Initiate each request but do not block
  7. $promises = [
  8. 'image' => $client->getAsync('/image'),
  9. 'png' => $client->getAsync('/image/png'),
  10. 'jpeg' => $client->getAsync('/image/jpeg'),
  11. 'webp' => $client->getAsync('/image/webp')
  12. ];
  13.  
  14. // Wait on all of the requests to complete. Throws a ConnectException
  15. // if any of the requests fail
  16. $results = Promise\unwrap($promises);
  17.  
  18. // Wait for the requests to complete, even if some of them fail
  19. $results = Promise\settle($promises)->wait();
  20.  
  21. // You can access each result using the key provided to the unwrap
  22. // function.
  23. echo $results['image']['value']->getHeader('Content-Length')[0]
  24. echo $results['png']['value']->getHeader('Content-Length')[0]

You can use the GuzzleHttp\Pool object when you have an indeterminateamount of requests you wish to send.

  1. use GuzzleHttp\Pool;
  2. use GuzzleHttp\Client;
  3. use GuzzleHttp\Psr7\Request;
  4.  
  5. $client = new Client();
  6.  
  7. $requests = function ($total) {
  8. $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
  9. for ($i = 0; $i < $total; $i++) {
  10. yield new Request('GET', $uri);
  11. }
  12. };
  13.  
  14. $pool = new Pool($client, $requests(100), [
  15. 'concurrency' => 5,
  16. 'fulfilled' => function ($response, $index) {
  17. // this is delivered each successful response
  18. },
  19. 'rejected' => function ($reason, $index) {
  20. // this is delivered each failed request
  21. },
  22. ]);
  23.  
  24. // Initiate the transfers and create a promise
  25. $promise = $pool->promise();
  26.  
  27. // Force the pool of requests to complete.
  28. $promise->wait();

Or using a closure that will return a promise once the pool calls the closure.

  1. $client = new Client();
  2.  
  3. $requests = function ($total) use ($client) {
  4. $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
  5. for ($i = 0; $i < $total; $i++) {
  6. yield function() use ($client, $uri) {
  7. return $client->getAsync($uri);
  8. };
  9. }
  10. };
  11.  
  12. $pool = new Pool($client, $requests(100));

Using Responses

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:

  1. $code = $response->getStatusCode(); // 200
  2. $reason = $response->getReasonPhrase(); // OK

You can retrieve headers from the response:

  1. // Check if a header exists.
  2. if ($response->hasHeader('Content-Length')) {
  3. echo "It exists";
  4. }
  5.  
  6. // Get a header from the response.
  7. echo $response->getHeader('Content-Length')[0];
  8.  
  9. // Get all of the response headers.
  10. foreach ($response->getHeaders() as $name => $values) {
  11. echo $name . ': ' . implode(', ', $values) . "\r\n";
  12. }

The body of a response can be retrieved using the getBody method. The bodycan be used as a string, cast to a string, or used as a stream like object.

  1. $body = $response->getBody();
  2. // Implicitly cast the body to a string and echo it
  3. echo $body;
  4. // Explicitly cast the body to a string
  5. $stringBody = (string) $body;
  6. // Read 10 bytes from the body
  7. $tenBytes = $body->read(10);
  8. // Read the remaining contents of the body as a string
  9. $remainingBytes = $body->getContents();

Query String Parameters

You can provide query string parameters with a request in several ways.

You can set query string parameters in the request's URI:

  1. $response = $client->request('GET', 'http://httpbin.org?foo=bar');

You can specify the query string parameters using the query requestoption as an array.

  1. $client->request('GET', 'http://httpbin.org', [
  2. 'query' => ['foo' => 'bar']
  3. ]);

Providing the option as an array will use PHP's http_build_query functionto format the query string.

And finally, you can provide the query request option as a string.

  1. $client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);

Uploading Data

Guzzle provides several methods for uploading data.

You can send requests that contain a stream of data by passing a string,resource returned from fopen, or an instance of aPsr\Http\Message\StreamInterface to the body request option.

  1. // Provide the body as a string.
  2. $r = $client->request('POST', 'http://httpbin.org/post', [
  3. 'body' => 'raw data'
  4. ]);
  5.  
  6. // Provide an fopen resource.
  7. $body = fopen('/path/to/file', 'r');
  8. $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
  9.  
  10. // Use the stream_for() function to create a PSR-7 stream.
  11. $body = \GuzzleHttp\Psr7\stream_for('hello!');
  12. $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:

  1. $r = $client->request('PUT', 'http://httpbin.org/put', [
  2. 'json' => ['foo' => 'bar']
  3. ]);

POST/Form Requests

In addition to specifying the raw data of a request using the body requestoption, Guzzle provides helpful abstractions over sending POST data.

Sending form fields

Sending application/x-www-form-urlencoded POST requests requires that youspecify the POST fields as an array in the form_params request options.

  1. $response = $client->request('POST', 'http://httpbin.org/post', [
  2. 'form_params' => [
  3. 'field_name' => 'abc',
  4. 'other_field' => '123',
  5. 'nested_field' => [
  6. 'nested' => 'hello'
  7. ]
  8. ]
  9. ]);

Sending form files

You can send files along with a form (multipart/form-data POST requests),using the multipart request option. multipart accepts an array ofassociative arrays, where each associative array contains the following keys:

  • name: (required, string) key mapping to the form field name.
  • contents: (required, mixed) Provide a string to send the contents of thefile as a string, provide an fopen resource to stream the contents from aPHP stream, or provide a Psr\Http\Message\StreamInterface to streamthe contents from a PSR-7 stream.
  1. $response = $client->request('POST', 'http://httpbin.org/post', [
  2. 'multipart' => [
  3. [
  4. 'name' => 'field_name',
  5. 'contents' => 'abc'
  6. ],
  7. [
  8. 'name' => 'file_name',
  9. 'contents' => fopen('/path/to/file', 'r')
  10. ],
  11. [
  12. 'name' => 'other_file',
  13. 'contents' => 'hello',
  14. 'filename' => 'filename.txt',
  15. 'headers' => [
  16. 'X-Foo' => 'this is an extra header to include'
  17. ]
  18. ]
  19. ]
  20. ]);

Cookies

Guzzle can maintain a cookie session for you if instructed using thecookies request option. When sending a request, the cookies optionmust be set to an instance of GuzzleHttp\Cookie\CookieJarInterface.

  1. // Use a specific cookie jar
  2. $jar = new \GuzzleHttp\Cookie\CookieJar;
  3. $r = $client->request('GET', 'http://httpbin.org/cookies', [
  4. 'cookies' => $jar
  5. ]);

You can set cookies to true in a client constructor if you would liketo use a shared cookie jar for all requests.

  1. // Use a shared client cookie jar
  2. $client = new \GuzzleHttp\Client(['cookies' => true]);
  3. $r = $client->request('GET', 'http://httpbin.org/cookies');

Redirects

Guzzle will automatically follow redirects unless you tell it not to. You cancustomize the redirect behavior using the allow_redirects request option.

  • Set to true to enable normal redirects with a maximum number of 5redirects. This is the default setting.
  • Set to false to disable redirects.
  • Pass an associative array containing the 'max' key to specify the maximumnumber of redirects and optionally provide a 'strict' key value to specifywhether or not to use strict RFC compliant redirects (meaning redirect POSTrequests with POST requests vs. doing what most browsers do which isredirect POST requests with GET requests).
  1. $response = $client->request('GET', 'http://github.com');
  2. echo $response->getStatusCode();
  3. // 200

The following example shows that redirects can be disabled.

  1. $response = $client->request('GET', 'http://github.com', [
  2. 'allow_redirects' => false
  3. ]);
  4. echo $response->getStatusCode();
  5. // 301

Exceptions

Guzzle throws exceptions for errors that occur during a transfer.

  • In the event of a networking error (connection timeout, DNS errors, etc.),a GuzzleHttp\Exception\RequestException is thrown. This exceptionextends from GuzzleHttp\Exception\TransferException. Catching thisexception will catch any exception that can be thrown while transferringrequests.
  1. use GuzzleHttp\Psr7;
  2. use GuzzleHttp\Exception\RequestException;
  3.  
  4. try {
  5. $client->request('GET', 'https://github.com/_abc_123_404');
  6. } catch (RequestException $e) {
  7. echo Psr7\str($e->getRequest());
  8. if ($e->hasResponse()) {
  9. echo Psr7\str($e->getResponse());
  10. }
  11. }
  • A GuzzleHttp\Exception\ConnectException exception is thrown in theevent of a networking error. This exception extends fromGuzzleHttp\Exception\RequestException.

  • A GuzzleHttp\Exception\ClientException is thrown for 400level errors if the http_errors request option is set to true. Thisexception extends from GuzzleHttp\Exception\BadResponseException andGuzzleHttp\Exception\BadResponseException extends fromGuzzleHttp\Exception\RequestException.

  1. use GuzzleHttp\Exception\ClientException;
  2.  
  3. try {
  4. $client->request('GET', 'https://github.com/_abc_123_404');
  5. } catch (ClientException $e) {
  6. echo Psr7\str($e->getRequest());
  7. echo Psr7\str($e->getResponse());
  8. }
  • A GuzzleHttp\Exception\ServerException is thrown for 500 levelerrors if the http_errors request option is set to true. Thisexception extends from GuzzleHttp\Exception\BadResponseException.

  • A GuzzleHttp\Exception\TooManyRedirectsException is thrown when toomany redirects are followed. This exception extends from GuzzleHttp\Exception\RequestException.

All of the above exceptions extend fromGuzzleHttp\Exception\TransferException.

Environment Variables

Guzzle exposes a few environment variables that can be used to customize thebehavior of the library.

GUZZLECURL_SELECT_TIMEOUT
Controls the duration in seconds that a curl_multi* handler will use whenselecting on curl handles using curl_multi_select(). Some systemshave issues with PHP's implementation of curl_multi_select() wherecalling this function always results in waiting for the maximum duration ofthe timeout.
HTTP_PROXY

Defines 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. See https://httpoxy.org for more information.
HTTPS_PROXY
Defines the proxy to use when sending requests using the "https" protocol.

Relevant ini Settings

Guzzle can utilize PHP ini settings when configuring clients.

openssl.cafile
Specifies the path on disk to a CA file in PEM format to use when sendingrequests over "https". See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults