You can customize requests created and transferred by a client usingrequest options. Request options control various aspects of a requestincluding, headers, query string parameters, timeout settings, the body of arequest, and much more.
All of the following examples use the following client:
$client=newGuzzleHttp\Client(['base_uri'=>'http://httpbin.org']);
Describes the redirect behavior of a request
[ 'max' => 5, 'strict' => false, 'referer' => false, 'protocols' => ['http', 'https'], 'track_redirects' => false]
GuzzleHttp\RequestOptions::ALLOW_REDIRECTS
Set tofalse to disable redirects.
$res=$client->request('GET','/redirect/3',['allow_redirects'=>false]);echo$res->getStatusCode();// 302
Set totrue (the default setting) to enable normal redirects with a maximumnumber of 5 redirects.
$res=$client->request('GET','/redirect/3');echo$res->getStatusCode();// 200
You can also pass an associative array containing the following key valuepairs:
max: (int, default=5) maximum number of allowed redirects.
strict: (bool, default=false) Set to true to use strict redirects.Strict RFC compliant redirects mean that POST redirect requests are sent asPOST requests vs. doing what most browsers do which is redirect POST requestswith GET requests.
referer: (bool, default=false) Set to true to enable adding the Refererheader when redirecting.
protocols: (array, default=['http', 'https']) Specified which protocols areallowed for redirect requests.
on_redirect: (callable) PHP callable that is invoked when a redirectis encountered. The callable is invoked with the original request and theredirect response that was received. Any return value from the on_redirectfunction is ignored.
track_redirects: (bool) When set totrue, each redirected URI and statuscode encountered will be tracked in theX-Guzzle-Redirect-History andX-Guzzle-Redirect-Status-History headers respectively. All URIs andstatus codes will be stored in the order which the redirects were encountered.
Note: When tracking redirects theX-Guzzle-Redirect-History header willexclude the initial request's URI and theX-Guzzle-Redirect-Status-Historyheader will exclude the final status code.
usePsr\Http\Message\RequestInterface;usePsr\Http\Message\ResponseInterface;usePsr\Http\Message\UriInterface;$onRedirect=function(RequestInterface$request,ResponseInterface$response,UriInterface$uri){echo'Redirecting! '.$request->getUri().' to '.$uri."\n";};$res=$client->request('GET','/redirect/3',['allow_redirects'=>['max'=>10,// allow at most 10 redirects.'strict'=>true,// use "strict" RFC compliant redirects.'referer'=>true,// add a Referer header'protocols'=>['https'],// only allow https URLs'on_redirect'=>$onRedirect,'track_redirects'=>true]]);echo$res->getStatusCode();// 200echo$res->getHeaderLine('X-Guzzle-Redirect-History');// http://first-redirect, http://second-redirect, etc...echo$res->getHeaderLine('X-Guzzle-Redirect-Status-History');// 301, 302, etc...
Warning
This option only has an effect if your handler has theGuzzleHttp\Middleware::redirect middleware. This middleware is addedby default when a client is created with no handler, and is added bydefault when creating a handler withGuzzleHttp\HandlerStack::create.
Note
This option hasno effect when making requests usingGuzzleHttp\Client::sendRequest(). In order to stay compliant with PSR-18 any redirect response is returned as is.
Pass an array of HTTP authentication parameters to use with therequest. The array must contain the username in index [0], the password inindex [1], and you can optionally provide a built-in authentication type inindex [2]. Passnull to disable authentication for a request.
None
GuzzleHttp\RequestOptions::AUTH
The built-in authentication types are as follows:
Authorization header (the default setting used if none isspecified).$client->request('GET','/get',['auth'=>['username','password']]);
$client->request('GET','/get',['auth'=>['username','password','digest']]);
Note
This is currently only supported when using the cURL handler, butcreating a replacement that can be used with any HTTP handler isplanned.
$client->request('GET','/get',['auth'=>['username','password','ntlm']]);
Note
This is currently only supported when using the cURL handler.
Thebody option is used to control the body of an entityenclosing request (e.g., PUT, POST, PATCH).
fopen() resourcePsr\Http\Message\StreamInterfaceNone
GuzzleHttp\RequestOptions::BODY
This setting can be set to any of the following types:
string
// You can send requests that use a string as the message body.$client->request('PUT','/put',['body'=>'foo']);
resource returned fromfopen()
// You can send requests that use a stream resource as the body.$resource=\GuzzleHttp\Psr7\Utils::tryFopen('http://httpbin.org','r');$client->request('PUT','/put',['body'=>$resource]);
Psr\Http\Message\StreamInterface
// You can send requests that use a Guzzle stream object as the body$stream=GuzzleHttp\Psr7\Utils::streamFor('contents...');$client->request('POST','/post',['body'=>$stream]);
Note
This option cannot be used withform_params,multipart, orjson
Set to a string to specify the path to a file containing a PEMformatted client side certificate. If a password is required, then set toan array containing the path to the PEM file in the first array elementfollowed by the password required for the certificate in the second arrayelement.
None
GuzzleHttp\RequestOptions::CERT
$client->request('GET','/',['cert'=>['/path/server.pem','password']]);
GuzzleHttp\Cookie\CookieJarInterfaceGuzzleHttp\RequestOptions::COOKIESYou must specify the cookies option as aGuzzleHttp\Cookie\CookieJarInterface orfalse.
$jar=new\GuzzleHttp\Cookie\CookieJar();$client->request('GET','/get',['cookies'=>$jar]);
Warning
This option only has an effect if your handler has theGuzzleHttp\Middleware::cookies middleware. This middleware is addedby default when a client is created with no handler, and is added bydefault when creating a handler withGuzzleHttp\default_handler.
Tip
When creating a client, you can set the default cookie option totrueto use a shared cookie session associated with the client.
0 to wait indefinitely (the default behavior).0GuzzleHttp\RequestOptions::CONNECT_TIMEOUT// Timeout if the client fails to connect to the server in 3.14 seconds.$client->request('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 cURLhandler.
Set totrue or set to a PHP stream returned byfopen() toenable debug output with the handler used to send a request. For example,when using cURL to transfer requests, cURL's verbose ofCURLOPT_VERBOSEwill be emitted. When using the PHP stream wrapper, stream wrappernotifications will be emitted. If set to true, the output is written toPHP's STDOUT. If a PHP stream is provided, output is written to the stream.
fopen() resourceNone
GuzzleHttp\RequestOptions::DEBUG
$client->request('GET','/get',['debug'=>true]);
Running the above example would output something like the following:
* About to connect() to httpbin.org port 80 (#0)* Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0)> GET /get HTTP/1.1Host: httpbin.orgUser-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7< HTTP/1.1 200 OK< Access-Control-Allow-Origin: *< Content-Type: application/json< Date: Sun, 16 Feb 2014 06:50:09 GMT< Server: gunicorn/0.17.4< Content-Length: 335< Connection: keep-alive<* Connection #0 to host httpbin.org left intact
Specify whether or notContent-Encoding responses (gzip,deflate, etc.) are automatically decoded.
true
GuzzleHttp\RequestOptions::DECODE_CONTENT
This option can be used to control how content-encoded response bodies arehandled. By default,decode_content is set to true, meaning any gzippedor deflated response will be decoded by Guzzle.
When set tofalse, the body of a response is never decoded, meaning thebytes pass through the handler unchanged.
// Request gzipped data, but do not decode it while downloading$client->request('GET','/foo.js',['headers'=>['Accept-Encoding'=>'gzip'],'decode_content'=>false]);
When set to a string, the bytes of a response are decoded and the string valueprovided to thedecode_content option is passed as theAccept-Encodingheader of the request.
// Pass "gzip" as the Accept-Encoding header.$client->request('GET','/foo.js',['decode_content'=>'gzip']);
The number of milliseconds to delay before sending the request.
null
GuzzleHttp\RequestOptions::DELAY
Controls the behavior of the "Expect: 100-Continue" header.
1048576
GuzzleHttp\RequestOptions::EXPECT
Set totrue to enable the "Expect: 100-Continue" header for all requeststhat sends a body. Set tofalse to disable the "Expect: 100-Continue"header for all requests. Set to a number so that the size of the payload mustbe greater than the number in order to send the Expect header. Setting to anumber will send the Expect header for all requests in which the size of thepayload cannot be determined or where the body is not rewindable.
By default, Guzzle will add the "Expect: 100-Continue" header when the size ofthe 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 andHTTP/2.0 protocols do not support the "Expect: 100-Continue" header.Support for handling the "Expect: 100-Continue" workflow must beimplemented by Guzzle HTTP handlers used by a client.
GuzzleHttp\RequestOptions::FORCE_IP_RESOLVE// Force ipv4 protocol$client->request('GET','/foo',['force_ip_resolve'=>'v4']);// Force ipv6 protocol$client->request('GET','/foo',['force_ip_resolve'=>'v6']);
Note
This setting must be supported by the HTTP handler used to send a request.force_ip_resolve is currently only supported by the built-in cURLand stream handlers.
GuzzleHttp\RequestOptions::FORM_PARAMSAssociative array of form field names to values where each value is a string orarray of strings. Sets the Content-Type header toapplication/x-www-form-urlencoded when no Content-Type header is alreadypresent.
$client->request('POST','/post',['form_params'=>['foo'=>'bar','baz'=>['hi','there!']]]);
Note
form_params cannot be used with themultipart option. You will need to useone or the other. Useform_params forapplication/x-www-form-urlencodedrequests, andmultipart formultipart/form-data requests.
This option cannot be used withbody,multipart, orjson
GuzzleHttp\RequestOptions::HEADERS// Set various headers on a request$client->request('GET','/get',['headers'=>['User-Agent'=>'testing/1.0','Accept'=>'application/json','X-Foo'=>['Bar','Baz']]]);
Headers may be added as default options when creating a client. When headersare used as default options, they are only applied if the request being createddoes not already contain the specific header. This includes both requests passedto the client in thesend() andsendAsync() methods, and requestscreated by the client (e.g.,request() andrequestAsync()).
$client=newGuzzleHttp\Client(['headers'=>['X-Foo'=>'Bar']]);// Will send a request with the X-Foo header.$client->request('GET','/get');// Sets the X-Foo header to "test", which prevents the default header// from being applied.$client->request('GET','/get',['headers'=>['X-Foo'=>'test']]);// Will disable adding in default headers.$client->request('GET','/get',['headers'=>null]);// Will not overwrite the X-Foo header because it is in the message.useGuzzleHttp\Psr7\Request;$request=newRequest('GET','http://foo.com',['X-Foo'=>'test']);$client->send($request);// Will overwrite the X-Foo header with the request option provided in the// send method.useGuzzleHttp\Psr7\Request;$request=newRequest('GET','http://foo.com',['X-Foo'=>'test']);$client->send($request,['headers'=>['X-Foo'=>'overwrite']]);
false to disable throwing exceptions on an HTTP protocolerrors (i.e., 4xx and 5xx responses). Exceptions are thrown by default whenHTTP protocol errors are encountered.trueGuzzleHttp\RequestOptions::HTTP_ERRORS$client->request('GET','/status/500');// Throws a GuzzleHttp\Exception\ServerException$res=$client->request('GET','/status/500',['http_errors'=>false]);echo$res->getStatusCode();// 500
Warning
This option only has an effect if your handler has theGuzzleHttp\Middleware::httpErrors middleware. This middleware is addedby default when a client is created with no handler, and is added bydefault when creating a handler withGuzzleHttp\default_handler.
Internationalized Domain Name (IDN) support (enabled by default ifintl extension is available).
true ifintl extension is available (and ICU library is 4.6+ for PHP 7.2+),false otherwise
GuzzleHttp\RequestOptions::IDN_CONVERSION
$client->request('GET','https://яндекс.рф');// яндекс.рф is translated to xn--d1acpjx3f.xn--p1ai before passing it to the handler$res=$client->request('GET','https://яндекс.рф',['idn_conversion'=>false]);// The domain part (яндекс.рф) stays unmodified
Enables/disables IDN support, can also be used for precise control by combiningIDNA_* constants (except IDNA_ERROR_*), see$options parameter inidn_to_ascii()documentation for more details.
json option is used to easily upload JSON encoded data as thebody of a request. A Content-Type header ofapplication/json will beadded if no Content-Type header is already present on the message.json_encode() function.GuzzleHttp\RequestOptions::JSON$response=$client->request('PUT','/put',['json'=>['foo'=>'bar']]);
Here's an example of using thetap middleware to see what request is sentover the wire.
useGuzzleHttp\Middleware;// Create a middleware that echoes parts of the request.$tapMiddleware=Middleware::tap(function($request){echo$request->getHeaderLine('Content-Type');// application/jsonecho$request->getBody();// {"foo":"bar"}});// The $handler variable is the handler passed in the// options to the client constructor.$response=$client->request('PUT','/put',['json'=>['foo'=>'bar'],'handler'=>$tapMiddleware($handler)]);
Note
This request option does not support customizing the Content-Type headeror any of the options from PHP'sjson_encode()function. If you need to customize these settings, then you must pass theJSON encoded data into the request yourself using thebody requestoption and you must specify the correct Content-Type header using theheaders request option.
This option cannot be used withbody,form_params, ormultipart
GuzzleHttp\RequestOptions::MULTIPARTThe value ofmultipart is an array of associative arrays, each containingthe following key value pairs:
name: (string, required) the form field namecontents: (StreamInterface/resource/string, required) The data to use inthe form element.headers: (array) Optional associative array of custom headers to use withthe form element.filename: (string) Optional string to send as the filename in the part.useGuzzleHttp\Psr7;$client->request('POST','/post',['multipart'=>[['name'=>'foo','contents'=>'data','headers'=>['X-Baz'=>'bar']],['name'=>'baz','contents'=>Psr7\Utils::tryFopen('/path/to/file','r')],['name'=>'qux','contents'=>Psr7\Utils::tryFopen('/path/to/file','r'),'filename'=>'custom_filename.txt'],]]);
Note
multipart cannot be used with theform_params option. You will need touse one or the other. Useform_params forapplication/x-www-form-urlencodedrequests, andmultipart formultipart/form-data requests.
This option cannot be used withbody,form_params, orjson
A callable that is invoked when the HTTP headers of the response havebeen received but the body has not yet begun to download.
GuzzleHttp\RequestOptions::ON_HEADERS
The callable accepts aPsr\Http\Message\ResponseInterface object. If an exceptionis thrown by the callable, then the promise associated with the response willbe rejected with aGuzzleHttp\Exception\RequestException that wraps theexception that was thrown.
You may need to know what headers and status codes were received before datacan be written to the sink.
// Reject responses that are greater than 1024 bytes.$client->request('GET','http://httpbin.org/stream/1024',['on_headers'=>function(ResponseInterface$response){if($response->getHeaderLine('Content-Length')>1024){thrownew\Exception('The file is too big!');}}]);
Note
When writing HTTP handlers, theon_headers function must be invokedbefore writing data to the body of the response.
on_stats allows you to get access to transfer statistics of arequest and access the lower level transfer details of the handlerassociated with your client.on_stats is a callable that is invokedwhen a handler has finished sending a request. The callback is invokedwith transfer statistics about the request, the response received, or theerror encountered. Included in the data is the total amount of time takento send the request.
GuzzleHttp\RequestOptions::ON_STATS
The callable accepts aGuzzleHttp\TransferStats object.
useGuzzleHttp\TransferStats;$client=newGuzzleHttp\Client();$client->request('GET','http://httpbin.org/stream/1024',['on_stats'=>function(TransferStats$stats){echo$stats->getEffectiveUri()."\n";echo$stats->getTransferTime()."\n";var_dump($stats->getHandlerStats());// You must check if a response was received before using the// response object.if($stats->hasResponse()){echo$stats->getResponse()->getStatusCode();}else{// Error data is handler specific. You will need to know what// type of error data your handler uses before using this// value.var_dump($stats->getHandlerErrorData());}}]);
Defines a function to invoke when transfer progress is made.
None
GuzzleHttp\RequestOptions::PROGRESS
The function accepts the following positional arguments:
// Send a GET request to /get?foo=bar$result=$client->request('GET','/',['progress'=>function($downloadTotal,$downloadedBytes,$uploadTotal,$uploadedBytes){//do something},]);
Pass a string to specify an HTTP proxy, or an array to specifydifferent proxies for different protocols.
None
GuzzleHttp\RequestOptions::PROXY
Pass a string to specify a proxy for all protocols.
$client->request('GET','/',['proxy'=>'http://localhost:8125']);
Pass an associative array to specify HTTP proxies for specific URI schemes(i.e., "http", "https"). Provide ano key value pair to provide a list ofhost names that should not be proxied to.
Note
Guzzle will automatically populate this value with your environment'sNO_PROXY environment variable. However, when providing aproxyrequest option, it is up to you to provide theno value parsed fromtheNO_PROXY environment variable(e.g.,explode(',',getenv('NO_PROXY'))).
$client->request('GET','/',['proxy'=>['http'=>'http://localhost:8125',// Use this proxy with "http"'https'=>'http://localhost:9124',// Use this proxy with "https",'no'=>['.mit.edu','foo.com']// Don't use a proxy with these]]);
Note
You can provide proxy URLs that contain a scheme, username, and password.For example,"http://username:password@192.168.16.1:10".
Associative array of query string values or query string to add tothe request.
None
GuzzleHttp\RequestOptions::QUERY
// Send a GET request to /get?foo=bar$client->request('GET','/get',['query'=>['foo'=>'bar']]);
Query strings specified in thequery option will overwrite all query stringvalues supplied in the URI of a request.
// Send a GET request to /get?foo=bar$client->request('GET','/get?abc=123',['query'=>['foo'=>'bar']]);
default_socket_timeout PHP ini settingGuzzleHttp\RequestOptions::READ_TIMEOUTThe timeout applies to individual read operations on a streamed body (when thestream option is enabled).
$response=$client->request('GET','/stream',['stream'=>true,'read_timeout'=>10,]);$body=$response->getBody();// Returns false on timeout$data=$body->read(1024);// Returns false on timeout$line=fgets($body->detach());
Specify where the body of a response will be saved.
fopen() resourcePsr\Http\Message\StreamInterfacePHP temp stream
GuzzleHttp\RequestOptions::SINK
Pass a string to specify the path to a file that will store the contents of theresponse body:
$client->request('GET','/stream/20',['sink'=>'/path/to/file']);
Pass a resource returned fromfopen() to write the response to a PHP stream:
$resource=\GuzzleHttp\Psr7\Utils::tryFopen('/path/to/file','w');$client->request('GET','/stream/20',['sink'=>$resource]);
Pass aPsr\Http\Message\StreamInterface object to stream the responsebody to an open PSR-7 stream.
$resource=\GuzzleHttp\Psr7\Utils::tryFopen('/path/to/file','w');$stream=\GuzzleHttp\Psr7\Utils::streamFor($resource);$client->request('GET','/stream/20',['save_to'=>$stream]);
Note
Thesave_to request option has been deprecated in favor of thesink request option. Providing thesave_to option is now an aliasofsink.
Specify the path to a file containing a private SSL key in PEMformat. If a password is required, then set to an array containing the pathto the SSL key in the first array element followed by the password requiredfor the certificate in the second element.
None
GuzzleHttp\RequestOptions::SSL_KEY
Note
ssl_key is implemented by HTTP handlers. This is currently onlysupported by the cURL handler, but might be supported by other third-parthandlers.
true to stream a response rather than download it allup-front.falseGuzzleHttp\RequestOptions::STREAM$response=$client->request('GET','/stream/20',['stream'=>true]);// Read bytes off of the stream until the end of the stream is reached$body=$response->getBody();while(!$body->eof()){echo$body->read(1024);}
Note
Streaming response support must be implemented by the HTTP handler used bya client. This option might not be supported by every HTTP handler, but theinterface of the response object remains the same regardless of whether ornot it is supported by the handler.
GuzzleHttp\RequestOptions::SYNCHRONOUSDescribes the SSL certificate verification behavior of a request.
true to enable SSL certificate verification and use the defaultCA bundle provided by operating system.false to disable certificate verification (this is insecure!).true
GuzzleHttp\RequestOptions::VERIFY
// Use the system's CA bundle (this is the default setting)$client->request('GET','/',['verify'=>true]);// Use a custom SSL certificate on disk.$client->request('GET','/',['verify'=>'/path/to/cert.pem']);// Disable validation entirely (don't do this!).$client->request('GET','/',['verify'=>false]);
If you do not need a specific certificate bundle, then Mozilla provides acommonly used CA bundle which can be downloadedhere(provided by the maintainer of cURL). Once you have a CA bundle available ondisk, you can set the "openssl.cafile" PHP ini setting to point to the path tothe file, allowing you to omit the "verify" request option. Much more detail onSSL certificates can be found on thecURL website.
0to wait indefinitely (the default behavior).0GuzzleHttp\RequestOptions::TIMEOUT// Timeout if a server does not return a response in 3.14 seconds.$client->request('GET','/delay/5',['timeout'=>3.14]);// PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\TransferException'
1.1GuzzleHttp\RequestOptions::VERSION// Force HTTP/1.0$request=$client->request('GET','/get',['version'=>1.0]);