Request Options

You can customize requests created by a client using request options. Request options control various aspects of a request including, headers, query string parameters, timeout settings, the body of a request, and much more.

All of the following examples use the following client:

  1. $client = new GuzzleHttp\Client(['base_url' => 'http://httpbin.org']);

headers

Summary:Associative array of headers to add to the request. Each key is the name of a header, and each value is a string or array of strings representing the header field values.
Types:array
Defaults:None
  1. // Set various headers on a request
  2. $client->get('/get', [
  3. 'headers' => [
  4. 'User-Agent' => 'testing/1.0',
  5. 'Accept' => 'application/json',
  6. 'X-Foo' => ['Bar', 'Baz']
  7. ]
  8. ]);

body

Summary:

The body option is used to control the body of an entity enclosing request (e.g., PUT, POST, PATCH).

Types:
  • string
  • fopen() resource
  • GuzzleHttp\Stream\StreamInterface
  • GuzzleHttp\Post\PostBodyInterface
Default:

None

This setting can be set to any of the following types:

  • string

    1. // You can send requests that use a string as the message body.
    2. $client->put('/put', ['body' => 'foo']);
  • resource returned from fopen()

    1. // You can send requests that use a stream resource as the body.
    2. $resource = fopen('http://httpbin.org', 'r');
    3. $client->put('/put', ['body' => $resource]);
  • Array

    Use an array to send POST style requests that use a GuzzleHttp\Post\PostBodyInterface object as the body.

    1. // You can send requests that use a POST body containing fields & files.
    2. $client->post('/post', [
    3. 'body' => [
    4. 'field' => 'abc',
    5. 'other_field' => '123',
    6. 'file_name' => fopen('/path/to/file', 'r')
    7. ]
    8. ]);
  • GuzzleHttp\Stream\StreamInterface

    1. // You can send requests that use a Guzzle stream object as the body
    2. $stream = GuzzleHttp\Stream\Stream::factory('contents...');
    3. $client->post('/post', ['body' => $stream]);

json

Summary:The json option is used to easily upload JSON encoded data as the body of a request. A Content-Type header of application/json will be added if no Content-Type header is already present on the message.
Types:Any PHP type that can be operated on by PHP’s json_encode() function.
Default:None
  1. $request = $client->createRequest('PUT', '/put', ['json' => ['foo' => 'bar']]);
  2. echo $request->getHeader('Content-Type');
  3. // application/json
  4. echo $request->getBody();
  5. // {"foo":"bar"}

Note

This request option does not support customizing the Content-Type header or any of the options from PHP’s json_encode() function. If you need to customize these settings, then you must pass the JSON encoded data into the request yourself using the body request option and you must specify the correct Content-Type header using the headers request option.

query

Summary:

Associative array of query string values to add to the request.

Types:
  • array
  • GuzzleHttp\Query
Default:

None

  1. // Send a GET request to /get?foo=bar
  2. $client->get('/get', ['query' => ['foo' => 'bar']]);

Query strings specified in the query option are combined with any query string values that are parsed from the URL.

  1. // Send a GET request to /get?abc=123&foo=bar
  2. $client->get('/get?abc=123', ['query' => ['foo' => 'bar']]);

auth

Summary:

Pass an array of HTTP authentication parameters to use with the request. The array must contain the username in index [0], the password in index [1], and you can optionally provide a built-in authentication type in index [2]. Pass null to disable authentication for a request.

Types:
  • array
  • string
  • null
Default:

None

The built-in authentication types are as follows:

basic

Use basic HTTP authentication in the Authorization header (the default setting used if none is specified).

  1. $client->get('/get', ['auth' => ['username', 'password']]);

digest

Use digest authentication (must be supported by the HTTP handler).

  1. $client->get('/get', ['auth' => ['username', 'password', 'digest']]);

This is currently only supported when using the cURL handler, but creating a replacement that can be used with any HTTP handler is planned.

Important

The authentication type (whether it’s provided as a string or as the third option in an array) is always converted to a lowercase string. Take this into account when implementing custom authentication types and when implementing custom message factories.

Custom Authentication Schemes

You can also provide a string representing a custom authentication type name. When using a custom authentication type string, you will need to implement the authentication method in an event listener that checks the auth request option of a request before it is sent. Authentication listeners that require a request is not modified after they are signed should have a very low priority to ensure that they are fired last or near last in the event chain.

  1. use GuzzleHttp\Event\BeforeEvent;
  2. use GuzzleHttp\Event\RequestEvents;
  3. /**
  4. * Custom authentication listener that handles the "foo" auth type.
  5. *
  6. * Listens to the "before" event of a request and only modifies the request
  7. * when the "auth" config setting of the request is "foo".
  8. */
  9. class FooAuth implements GuzzleHttp\Event\SubscriberInterface
  10. {
  11. private $password;
  12. public function __construct($password)
  13. {
  14. $this->password = $password;
  15. }
  16. public function getEvents()
  17. {
  18. return ['before' => ['sign', RequestEvents::SIGN_REQUEST]];
  19. }
  20. public function sign(BeforeEvent $e)
  21. {
  22. if ($e->getRequest()->getConfig()['auth'] == 'foo') {
  23. $e->getRequest()->setHeader('X-Foo', 'Foo ' . $this->password);
  24. }
  25. }
  26. }
  27. $client->getEmitter()->attach(new FooAuth('password'));
  28. $client->get('/', ['auth' => 'foo']);

Adapter Specific Authentication Schemes

If you need to use authentication methods provided by cURL (e.g., NTLM, GSS, etc.), then you need to specify a curl handler option in the options request option array. See config for more information.

cookies

Summary:

Specifies whether or not cookies are used in a request or what cookie jar to use or what cookies to send.

Types:
  • bool
  • array
  • GuzzleHttp\Cookie\CookieJarInterface
Default:

None

Set to true to use a shared cookie session associated with the client.

  1. // Enable cookies using the shared cookie jar of the client.
  2. $client->get('/get', ['cookies' => true]);

Pass an associative array containing cookies to send in the request and start a new cookie session.

  1. // Enable cookies and send specific cookies
  2. $client->get('/get', ['cookies' => ['foo' => 'bar']]);

Set to a GuzzleHttp\Cookie\CookieJarInterface object to use an existing cookie jar.

  1. $jar = new GuzzleHttp\Cookie\CookieJar();
  2. $client->get('/get', ['cookies' => $jar]);

allow_redirects

Summary:

Describes the redirect behavior of a request

Types:
  • bool
  • array
Default:
  1. [
  2. max => 5,
  3. strict => false,
  4. referer => true,
  5. protocols => [‘http’, https’]
  6. ]

Set to false to disable redirects.

  1. $res = $client->get('/redirect/3', ['allow_redirects' => false]);
  2. echo $res->getStatusCode();
  3. // 302

Set to true (the default setting) to enable normal redirects with a maximum number of 5 redirects.

  1. $res = $client->get('/redirect/3');
  2. echo $res->getStatusCode();
  3. // 200

Pass an associative array containing the ‘max’ key to specify the maximum number of redirects, provide a ‘strict’ key value to specify whether or not to use strict RFC compliant redirects (meaning redirect POST requests with POST requests vs. doing what most browsers do which is redirect POST requests with GET requests), provide a ‘referer’ key to specify whether or not the “Referer” header should be added when redirecting, and provide a ‘protocols’ array that specifies which protocols are supported for redirects (defaults to ['http', 'https']).

  1. $res = $client->get('/redirect/3', [
  2. 'allow_redirects' => [
  3. 'max' => 10, // allow at most 10 redirects.
  4. 'strict' => true, // use "strict" RFC compliant redirects.
  5. 'referer' => true, // add a Referer header
  6. 'protocols' => ['https'] // only allow https URLs
  7. ]
  8. ]);
  9. echo $res->getStatusCode();
  10. // 200

decode_content

Summary:

Specify whether or not Content-Encoding responses (gzip, deflate, etc.) are automatically decoded.

Types:
  • string
  • bool
Default:

true

This option can be used to control how content-encoded response bodies are handled. By default, decode_content is set to true, meaning any gzipped or deflated response will be decoded by Guzzle.

When set to false, the body of a response is never decoded, meaning the bytes pass through the handler unchanged.

  1. // Request gzipped data, but do not decode it while downloading
  2. $client->get('/foo.js', [
  3. 'headers' => ['Accept-Encoding' => 'gzip'],
  4. 'decode_content' => false
  5. ]);

When set to a string, the bytes of a response are decoded and the string value provided to the decode_content option is passed as the Accept-Encoding header of the request.

  1. // Pass "gzip" as the Accept-Encoding header.
  2. $client->get('/foo.js', ['decode_content' => 'gzip']);

save_to

Summary:

Specify where the body of a response will be saved.

Types:
  • string
  • fopen() resource
  • GuzzleHttp\Stream\StreamInterface
Default:

PHP temp stream

Pass a string to specify the path to a file that will store the contents of the response body:

  1. $client->get('/stream/20', ['save_to' => '/path/to/file']);

Pass a resource returned from fopen() to write the response to a PHP stream:

  1. $resource = fopen('/path/to/file', 'w');
  2. $client->get('/stream/20', ['save_to' => $resource]);

Pass a GuzzleHttp\Stream\StreamInterface object to stream the response body to an open Guzzle stream:

  1. $resource = fopen('/path/to/file', 'w');
  2. $stream = GuzzleHttp\Stream\Stream::factory($resource);
  3. $client->get('/stream/20', ['save_to' => $stream]);

events

Summary:An associative array mapping event names to a callable. Or an associative array containing the ‘fn’ key that maps to a callable, an optional ‘priority’ key used to specify the event priority, and an optional ‘once’ key used to specify if the event should remove itself the first time it is triggered.
Types:array
Default:None
  1. use GuzzleHttp\Event\BeforeEvent;
  2. use GuzzleHttp\Event\HeadersEvent;
  3. use GuzzleHttp\Event\CompleteEvent;
  4. use GuzzleHttp\Event\ErrorEvent;
  5. $client->get('/', [
  6. 'events' => [
  7. 'before' => function (BeforeEvent $e) { echo 'Before'; },
  8. 'complete' => function (CompleteEvent $e) { echo 'Complete'; },
  9. 'error' => function (ErrorEvent $e) { echo 'Error'; },
  10. ]
  11. ]);

Here’s an example of using the associative array format for control over the priority and whether or not an event should be triggered more than once.

  1. $client->get('/', [
  2. 'events' => [
  3. 'before' => [
  4. 'fn' => function (BeforeEvent $e) { echo 'Before'; },
  5. 'priority' => 100,
  6. 'once' => true
  7. ]
  8. ]
  9. ]);

subscribers

Summary:Array of event subscribers to add to the request. Each value in the array must be an instance of GuzzleHttp\Event\SubscriberInterface.
Types:array
Default:None
  1. use GuzzleHttp\Subscriber\History;
  2. use GuzzleHttp\Subscriber\Mock;
  3. use GuzzleHttp\Message\Response;
  4. $history = new History();
  5. $mock = new Mock([new Response(200)]);
  6. $client->get('/', ['subscribers' => [$history, $mock]]);
  7. echo $history;
  8. // Outputs the request and response history

exceptions

Summary:Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when HTTP protocol errors are encountered.
Types:bool
Default:true
  1. $client->get('/status/500');
  2. // Throws a GuzzleHttp\Exception\ServerException
  3. $res = $client->get('/status/500', ['exceptions' => false]);
  4. echo $res->getStatusCode();
  5. // 500

timeout

Summary:Float describing the timeout of the request in seconds. Use 0 to wait indefinitely (the default behavior).
Types:float
Default:0
  1. // Timeout if a server does not return a response in 3.14 seconds.
  2. $client->get('/delay/5', ['timeout' => 3.14]);
  3. // PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException'

connect_timeout

Summary:Float describing the number of seconds to wait while trying to connect to a server. Use 0 to wait indefinitely (the default behavior).
Types:float
Default:0
  1. // Timeout if the client fails to connect to the server in 3.14 seconds.
  2. $client->get('/delay/5', ['connect_timeout' => 3.14]);

Note

This setting must be supported by the HTTP handler used to send a request. connect_timeout is currently only supported by the built-in cURL handler.

verify

Summary:

Describes the SSL certificate verification behavior of a request.

  • Set to true to enable SSL certificate verification and use the default CA bundle provided by operating system.
  • Set to false to disable certificate verification (this is insecure!).
  • Set to a string to provide the path to a CA bundle to enable verification using a custom certificate.
Types:
  • bool
  • string
Default:

true

  1. // Use the system's CA bundle (this is the default setting)
  2. $client->get('/', ['verify' => true]);
  3. // Use a custom SSL certificate on disk.
  4. $client->get('/', ['verify' => '/path/to/cert.pem']);
  5. // Disable validation entirely (don't do this!).
  6. $client->get('/', ['verify' => false]);

Not all system’s have a known CA bundle on disk. For example, Windows and OS X do not have a single common location for CA bundles. When setting “verify” to true, Guzzle will do its best to find the most appropriate CA bundle on your system. When using cURL or the PHP stream wrapper on PHP versions >= 5.6, this happens by default. When using the PHP stream wrapper on versions < 5.6, Guzzle tries to find your CA bundle in the following order:

  1. Check if openssl.cafile is set in your php.ini file.
  2. Check if curl.cainfo is set in your php.ini file.
  3. Check if /etc/pki/tls/certs/ca-bundle.crt exists (Red Hat, CentOS, Fedora; provided by the ca-certificates package)
  4. Check if /etc/ssl/certs/ca-certificates.crt exists (Ubuntu, Debian; provided by the ca-certificates package)
  5. Check if /usr/local/share/certs/ca-root-nss.crt exists (FreeBSD; provided by the ca_root_nss package)
  6. Check if /usr/local/etc/openssl/cert.pem (OS X; provided by homebrew)
  7. Check if C:\windows\system32\curl-ca-bundle.crt exists (Windows)
  8. Check if C:\windows\curl-ca-bundle.crt exists (Windows)

The result of this lookup is cached in memory so that subsequent calls in the same process will return very quickly. However, when sending only a single request per-process in something like Apache, you should consider setting the openssl.cafile environment variable to the path on disk to the file so that this entire process is skipped.

If you do not need a specific certificate bundle, then Mozilla provides a commonly used CA bundle which can be downloaded here (provided by the maintainer of cURL). Once you have a CA bundle available on disk, you can set the “openssl.cafile” PHP ini setting to point to the path to the file, allowing you to omit the “verify” request option. Much more detail on SSL certificates can be found on the cURL website.

cert

Summary:

Set to a string to specify the path to a file containing a PEM formatted client side certificate. If a password is required, then set to an array containing the path to the PEM file in the first array element followed by the password required for the certificate in the second array element.

Types:
  • string
  • array
Default:

None

  1. $client->get('/', ['cert' => ['/path/server.pem', 'password']]);

ssl_key

Summary:

Specify the path to a file containing a private SSL key in PEM format. If a password is required, then set to an array containing the path to the SSL key in the first array element followed by the password required for the certificate in the second element.

Types:
  • string
  • array
Default:

None

Note

ssl_key is implemented by HTTP handlers. This is currently only supported by the cURL handler, but might be supported by other third-part handlers.

proxy

Summary:

Pass a string to specify an HTTP proxy, or an array to specify different proxies for different protocols.

Types:
  • string
  • array
Default:

None

Pass a string to specify a proxy for all protocols.

  1. $client->get('/', ['proxy' => 'tcp://localhost:8125']);

Pass an associative array to specify HTTP proxies for specific URI schemes (i.e., “http”, “https”).

  1. $client->get('/', [
  2. 'proxy' => [
  3. 'http' => 'tcp://localhost:8125', // Use this proxy with "http"
  4. 'https' => 'tcp://localhost:9124' // Use this proxy with "https"
  5. ]
  6. ]);

Note

You can provide proxy URLs that contain a scheme, username, and password. For example, "http://username:password@192.168.16.1:10".

debug

Summary:

Set to true or set to a PHP stream returned by fopen() to enable debug output with the handler used to send a request. For example, when using cURL to transfer requests, cURL’s verbose of CURLOPT_VERBOSE will be emitted. When using the PHP stream wrapper, stream wrapper notifications will be emitted. If set to true, the output is written to PHP’s STDOUT. If a PHP stream is provided, output is written to the stream.

Types:
  • bool
  • fopen() resource
Default:

None

  1. $client->get('/get', ['debug' => true]);

Running the above example would output something like the following:

  1. * About to connect() to httpbin.org port 80 (#0)
  2. * Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0)
  3. > GET /get HTTP/1.1
  4. Host: httpbin.org
  5. User-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7
  6. < HTTP/1.1 200 OK
  7. < Access-Control-Allow-Origin: *
  8. < Content-Type: application/json
  9. < Date: Sun, 16 Feb 2014 06:50:09 GMT
  10. < Server: gunicorn/0.17.4
  11. < Content-Length: 335
  12. < Connection: keep-alive
  13. <
  14. * Connection #0 to host httpbin.org left intact

stream

Summary:Set to true to stream a response rather than download it all up-front.
Types:bool
Default:false
  1. $response = $client->get('/stream/20', ['stream' => true]);
  2. // Read bytes off of the stream until the end of the stream is reached
  3. $body = $response->getBody();
  4. while (!$body->eof()) {
  5. echo $body->read(1024);
  6. }

Note

Streaming response support must be implemented by the HTTP handler used by a client. This option might not be supported by every HTTP handler, but the interface of the response object remains the same regardless of whether or not it is supported by the handler.

expect

Summary:

Controls the behavior of the “Expect: 100-Continue” header.

Types:
  • bool
  • integer
Default:

1048576

Set to true to enable the “Expect: 100-Continue” header for all requests that sends a body. Set to false to disable the “Expect: 100-Continue” header for all requests. Set to a number so that the size of the payload must be greater than the number in order to send the Expect header. Setting to a number will send the Expect header for all requests in which the size of the payload cannot be determined or where the body is not rewindable.

By default, Guzzle will add the “Expect: 100-Continue” header when the size of the body of a request is greater than 1 MB and a request is using HTTP/1.1.

Note

This option only takes effect when using HTTP/1.1. The HTTP/1.0 and HTTP/2.0 protocols do not support the “Expect: 100-Continue” header. Support for handling the “Expect: 100-Continue” workflow must be implemented by Guzzle HTTP handlers used by a client.

version

Summary:Protocol version to use with the request.
Types:string, float
Default:1.1
  1. // Force HTTP/1.0
  2. $request = $client->createRequest('GET', '/get', ['version' => 1.0]);
  3. echo $request->getProtocolVersion();
  4. // 1.0

config

Summary:Associative array of config options that are forwarded to a request’s configuration collection. These values are used as configuration options that can be consumed by plugins and handlers.
Types:array
Default:None
  1. $request = $client->createRequest('GET', '/get', ['config' => ['foo' => 'bar']]);
  2. echo $request->getConfig('foo');
  3. // 'bar'

Some HTTP handlers allow you to specify custom handler-specific settings. For example, you can pass custom cURL options to requests by passing an associative array in the config request option under the curl key.

  1. // Use custom cURL options with the request. This example uses NTLM auth
  2. // to authenticate with a server.
  3. $client->get('/', [
  4. 'config' => [
  5. 'curl' => [
  6. CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
  7. CURLOPT_USERPWD => 'username:password'
  8. ]
  9. ]
  10. ]);

future

Summary:

Specifies whether or not a response SHOULD be an instance of a GuzzleHttp\Message\FutureResponse object.

Types:
  • bool
  • string
Default:

false

By default, Guzzle requests should be synchronous. You can create asynchronous future responses by passing the future request option as true. The response will only be executed when it is used like a normal response, the wait() method of the response is called, or the corresponding handler that created the response is destructing and there are futures that have not been resolved.

Important

This option only has an effect if your handler can create and return future responses. However, even if a response is completed synchronously, Guzzle will ensure that a FutureResponse object is returned for API consistency.

  1. $response = $client->get('/foo', ['future' => true])
  2. ->then(function ($response) {
  3. echo 'I got a response! ' . $response;
  4. });