request-options.rst 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. ===============
  2. Request Options
  3. ===============
  4. You can customize requests created and transferred by a client using
  5. **request options**. Request options control various aspects of a request
  6. including, headers, query string parameters, timeout settings, the body of a
  7. request, and much more.
  8. All of the following examples use the following client:
  9. .. code-block:: php
  10. $client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org']);
  11. .. _allow_redirects-option:
  12. allow_redirects
  13. ---------------
  14. :Summary: Describes the redirect behavior of a request
  15. :Types:
  16. - bool
  17. - array
  18. :Default:
  19. ::
  20. [
  21. 'max' => 5,
  22. 'strict' => false,
  23. 'referer' => false,
  24. 'protocols' => ['http', 'https'],
  25. 'track_redirects' => false
  26. ]
  27. :Constant: ``GuzzleHttp\RequestOptions::ALLOW_REDIRECTS``
  28. Set to ``false`` to disable redirects.
  29. .. code-block:: php
  30. $res = $client->request('GET', '/redirect/3', ['allow_redirects' => false]);
  31. echo $res->getStatusCode();
  32. // 302
  33. Set to ``true`` (the default setting) to enable normal redirects with a maximum
  34. number of 5 redirects.
  35. .. code-block:: php
  36. $res = $client->request('GET', '/redirect/3');
  37. echo $res->getStatusCode();
  38. // 200
  39. You can also pass an associative array containing the following key value
  40. pairs:
  41. - max: (int, default=5) maximum number of allowed redirects.
  42. - strict: (bool, default=false) Set to true to use strict redirects.
  43. Strict RFC compliant redirects mean that POST redirect requests are sent as
  44. POST requests vs. doing what most browsers do which is redirect POST requests
  45. with GET requests.
  46. - referer: (bool, default=false) Set to true to enable adding the Referer
  47. header when redirecting.
  48. - protocols: (array, default=['http', 'https']) Specified which protocols are
  49. allowed for redirect requests.
  50. - on_redirect: (callable) PHP callable that is invoked when a redirect
  51. is encountered. The callable is invoked with the original request and the
  52. redirect response that was received. Any return value from the on_redirect
  53. function is ignored.
  54. - track_redirects: (bool) When set to ``true``, each redirected URI and status
  55. code encountered will be tracked in the ``X-Guzzle-Redirect-History`` and
  56. ``X-Guzzle-Redirect-Status-History`` headers respectively. All URIs and
  57. status codes will be stored in the order which the redirects were encountered.
  58. Note: When tracking redirects the ``X-Guzzle-Redirect-History`` header will
  59. exclude the initial request's URI and the ``X-Guzzle-Redirect-Status-History``
  60. header will exclude the final status code.
  61. .. code-block:: php
  62. use Psr\Http\Message\RequestInterface;
  63. use Psr\Http\Message\ResponseInterface;
  64. use Psr\Http\Message\UriInterface;
  65. $onRedirect = function(
  66. RequestInterface $request,
  67. ResponseInterface $response,
  68. UriInterface $uri
  69. ) {
  70. echo 'Redirecting! ' . $request->getUri() . ' to ' . $uri . "\n";
  71. };
  72. $res = $client->request('GET', '/redirect/3', [
  73. 'allow_redirects' => [
  74. 'max' => 10, // allow at most 10 redirects.
  75. 'strict' => true, // use "strict" RFC compliant redirects.
  76. 'referer' => true, // add a Referer header
  77. 'protocols' => ['https'], // only allow https URLs
  78. 'on_redirect' => $onRedirect,
  79. 'track_redirects' => true
  80. ]
  81. ]);
  82. echo $res->getStatusCode();
  83. // 200
  84. echo $res->getHeaderLine('X-Guzzle-Redirect-History');
  85. // http://first-redirect, http://second-redirect, etc...
  86. echo $res->getHeaderLine('X-Guzzle-Redirect-Status-History');
  87. // 301, 302, etc...
  88. .. warning::
  89. This option only has an effect if your handler has the
  90. ``GuzzleHttp\Middleware::redirect`` middleware. This middleware is added
  91. by default when a client is created with no handler, and is added by
  92. default when creating a handler with ``GuzzleHttp\HandlerStack::create``.
  93. auth
  94. ----
  95. :Summary: Pass an array of HTTP authentication parameters to use with the
  96. request. The array must contain the username in index [0], the password in
  97. index [1], and you can optionally provide a built-in authentication type in
  98. index [2]. Pass ``null`` to disable authentication for a request.
  99. :Types:
  100. - array
  101. - string
  102. - null
  103. :Default: None
  104. :Constant: ``GuzzleHttp\RequestOptions::AUTH``
  105. The built-in authentication types are as follows:
  106. basic
  107. Use `basic HTTP authentication <http://www.ietf.org/rfc/rfc2069.txt>`_
  108. in the ``Authorization`` header (the default setting used if none is
  109. specified).
  110. .. code-block:: php
  111. $client->request('GET', '/get', ['auth' => ['username', 'password']]);
  112. digest
  113. Use `digest authentication <http://www.ietf.org/rfc/rfc2069.txt>`_
  114. (must be supported by the HTTP handler).
  115. .. code-block:: php
  116. $client->request('GET', '/get', [
  117. 'auth' => ['username', 'password', 'digest']
  118. ]);
  119. .. note::
  120. This is currently only supported when using the cURL handler, but
  121. creating a replacement that can be used with any HTTP handler is
  122. planned.
  123. ntlm
  124. Use `Microsoft NTLM authentication <https://msdn.microsoft.com/en-us/library/windows/desktop/aa378749(v=vs.85).aspx>`_
  125. (must be supported by the HTTP handler).
  126. .. code-block:: php
  127. $client->request('GET', '/get', [
  128. 'auth' => ['username', 'password', 'ntlm']
  129. ]);
  130. .. note::
  131. This is currently only supported when using the cURL handler.
  132. body
  133. ----
  134. :Summary: The ``body`` option is used to control the body of an entity
  135. enclosing request (e.g., PUT, POST, PATCH).
  136. :Types:
  137. - string
  138. - ``fopen()`` resource
  139. - ``Psr\Http\Message\StreamInterface``
  140. :Default: None
  141. :Constant: ``GuzzleHttp\RequestOptions::BODY``
  142. This setting can be set to any of the following types:
  143. - string
  144. .. code-block:: php
  145. // You can send requests that use a string as the message body.
  146. $client->request('PUT', '/put', ['body' => 'foo']);
  147. - resource returned from ``fopen()``
  148. .. code-block:: php
  149. // You can send requests that use a stream resource as the body.
  150. $resource = fopen('http://httpbin.org', 'r');
  151. $client->request('PUT', '/put', ['body' => $resource]);
  152. - ``Psr\Http\Message\StreamInterface``
  153. .. code-block:: php
  154. // You can send requests that use a Guzzle stream object as the body
  155. $stream = GuzzleHttp\Psr7\stream_for('contents...');
  156. $client->request('POST', '/post', ['body' => $stream]);
  157. .. note::
  158. This option cannot be used with ``form_params``, ``multipart``, or ``json``
  159. .. _cert-option:
  160. cert
  161. ----
  162. :Summary: Set to a string to specify the path to a file containing a PEM
  163. formatted client side certificate. If a password is required, then set to
  164. an array containing the path to the PEM file in the first array element
  165. followed by the password required for the certificate in the second array
  166. element.
  167. :Types:
  168. - string
  169. - array
  170. :Default: None
  171. :Constant: ``GuzzleHttp\RequestOptions::CERT``
  172. .. code-block:: php
  173. $client->request('GET', '/', ['cert' => ['/path/server.pem', 'password']]);
  174. .. _cookies-option:
  175. cookies
  176. -------
  177. :Summary: Specifies whether or not cookies are used in a request or what cookie
  178. jar to use or what cookies to send.
  179. :Types: ``GuzzleHttp\Cookie\CookieJarInterface``
  180. :Default: None
  181. :Constant: ``GuzzleHttp\RequestOptions::COOKIES``
  182. You must specify the cookies option as a
  183. ``GuzzleHttp\Cookie\CookieJarInterface`` or ``false``.
  184. .. code-block:: php
  185. $jar = new \GuzzleHttp\Cookie\CookieJar();
  186. $client->request('GET', '/get', ['cookies' => $jar]);
  187. .. warning::
  188. This option only has an effect if your handler has the
  189. ``GuzzleHttp\Middleware::cookies`` middleware. This middleware is added
  190. by default when a client is created with no handler, and is added by
  191. default when creating a handler with ``GuzzleHttp\default_handler``.
  192. .. tip::
  193. When creating a client, you can set the default cookie option to ``true``
  194. to use a shared cookie session associated with the client.
  195. .. _connect_timeout-option:
  196. connect_timeout
  197. ---------------
  198. :Summary: Float describing the number of seconds to wait while trying to connect
  199. to a server. Use ``0`` to wait indefinitely (the default behavior).
  200. :Types: float
  201. :Default: ``0``
  202. :Constant: ``GuzzleHttp\RequestOptions::CONNECT_TIMEOUT``
  203. .. code-block:: php
  204. // Timeout if the client fails to connect to the server in 3.14 seconds.
  205. $client->request('GET', '/delay/5', ['connect_timeout' => 3.14]);
  206. .. note::
  207. This setting must be supported by the HTTP handler used to send a request.
  208. ``connect_timeout`` is currently only supported by the built-in cURL
  209. handler.
  210. .. _debug-option:
  211. debug
  212. -----
  213. :Summary: Set to ``true`` or set to a PHP stream returned by ``fopen()`` to
  214. enable debug output with the handler used to send a request. For example,
  215. when using cURL to transfer requests, cURL's verbose of ``CURLOPT_VERBOSE``
  216. will be emitted. When using the PHP stream wrapper, stream wrapper
  217. notifications will be emitted. If set to true, the output is written to
  218. PHP's STDOUT. If a PHP stream is provided, output is written to the stream.
  219. :Types:
  220. - bool
  221. - ``fopen()`` resource
  222. :Default: None
  223. :Constant: ``GuzzleHttp\RequestOptions::DEBUG``
  224. .. code-block:: php
  225. $client->request('GET', '/get', ['debug' => true]);
  226. Running the above example would output something like the following:
  227. ::
  228. * About to connect() to httpbin.org port 80 (#0)
  229. * Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0)
  230. > GET /get HTTP/1.1
  231. Host: httpbin.org
  232. User-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7
  233. < HTTP/1.1 200 OK
  234. < Access-Control-Allow-Origin: *
  235. < Content-Type: application/json
  236. < Date: Sun, 16 Feb 2014 06:50:09 GMT
  237. < Server: gunicorn/0.17.4
  238. < Content-Length: 335
  239. < Connection: keep-alive
  240. <
  241. * Connection #0 to host httpbin.org left intact
  242. .. _decode_content-option:
  243. decode_content
  244. --------------
  245. :Summary: Specify whether or not ``Content-Encoding`` responses (gzip,
  246. deflate, etc.) are automatically decoded.
  247. :Types:
  248. - string
  249. - bool
  250. :Default: ``true``
  251. :Constant: ``GuzzleHttp\RequestOptions::DECODE_CONTENT``
  252. This option can be used to control how content-encoded response bodies are
  253. handled. By default, ``decode_content`` is set to true, meaning any gzipped
  254. or deflated response will be decoded by Guzzle.
  255. When set to ``false``, the body of a response is never decoded, meaning the
  256. bytes pass through the handler unchanged.
  257. .. code-block:: php
  258. // Request gzipped data, but do not decode it while downloading
  259. $client->request('GET', '/foo.js', [
  260. 'headers' => ['Accept-Encoding' => 'gzip'],
  261. 'decode_content' => false
  262. ]);
  263. When set to a string, the bytes of a response are decoded and the string value
  264. provided to the ``decode_content`` option is passed as the ``Accept-Encoding``
  265. header of the request.
  266. .. code-block:: php
  267. // Pass "gzip" as the Accept-Encoding header.
  268. $client->request('GET', '/foo.js', ['decode_content' => 'gzip']);
  269. .. _delay-option:
  270. delay
  271. -----
  272. :Summary: The number of milliseconds to delay before sending the request.
  273. :Types:
  274. - integer
  275. - float
  276. :Default: null
  277. :Constant: ``GuzzleHttp\RequestOptions::DELAY``
  278. .. _expect-option:
  279. expect
  280. ------
  281. :Summary: Controls the behavior of the "Expect: 100-Continue" header.
  282. :Types:
  283. - bool
  284. - integer
  285. :Default: ``1048576``
  286. :Constant: ``GuzzleHttp\RequestOptions::EXPECT``
  287. Set to ``true`` to enable the "Expect: 100-Continue" header for all requests
  288. that sends a body. Set to ``false`` to disable the "Expect: 100-Continue"
  289. header for all requests. Set to a number so that the size of the payload must
  290. be greater than the number in order to send the Expect header. Setting to a
  291. number will send the Expect header for all requests in which the size of the
  292. payload cannot be determined or where the body is not rewindable.
  293. By default, Guzzle will add the "Expect: 100-Continue" header when the size of
  294. the body of a request is greater than 1 MB and a request is using HTTP/1.1.
  295. .. note::
  296. This option only takes effect when using HTTP/1.1. The HTTP/1.0 and
  297. HTTP/2.0 protocols do not support the "Expect: 100-Continue" header.
  298. Support for handling the "Expect: 100-Continue" workflow must be
  299. implemented by Guzzle HTTP handlers used by a client.
  300. force_ip_resolve
  301. ----------------
  302. :Summary: Set to "v4" if you want the HTTP handlers to use only ipv4 protocol or "v6" for ipv6 protocol.
  303. :Types: string
  304. :Default: null
  305. :Constant: ``GuzzleHttp\RequestOptions::FORCE_IP_RESOLVE``
  306. .. code-block:: php
  307. // Force ipv4 protocol
  308. $client->request('GET', '/foo', ['force_ip_resolve' => 'v4']);
  309. // Force ipv6 protocol
  310. $client->request('GET', '/foo', ['force_ip_resolve' => 'v6']);
  311. .. note::
  312. This setting must be supported by the HTTP handler used to send a request.
  313. ``force_ip_resolve`` is currently only supported by the built-in cURL
  314. and stream handlers.
  315. form_params
  316. -----------
  317. :Summary: Used to send an `application/x-www-form-urlencoded` POST request.
  318. :Types: array
  319. :Constant: ``GuzzleHttp\RequestOptions::FORM_PARAMS``
  320. Associative array of form field names to values where each value is a string or
  321. array of strings. Sets the Content-Type header to
  322. application/x-www-form-urlencoded when no Content-Type header is already
  323. present.
  324. .. code-block:: php
  325. $client->request('POST', '/post', [
  326. 'form_params' => [
  327. 'foo' => 'bar',
  328. 'baz' => ['hi', 'there!']
  329. ]
  330. ]);
  331. .. note::
  332. ``form_params`` cannot be used with the ``multipart`` option. You will need to use
  333. one or the other. Use ``form_params`` for ``application/x-www-form-urlencoded``
  334. requests, and ``multipart`` for ``multipart/form-data`` requests.
  335. This option cannot be used with ``body``, ``multipart``, or ``json``
  336. headers
  337. -------
  338. :Summary: Associative array of headers to add to the request. Each key is the
  339. name of a header, and each value is a string or array of strings
  340. representing the header field values.
  341. :Types: array
  342. :Defaults: None
  343. :Constant: ``GuzzleHttp\RequestOptions::HEADERS``
  344. .. code-block:: php
  345. // Set various headers on a request
  346. $client->request('GET', '/get', [
  347. 'headers' => [
  348. 'User-Agent' => 'testing/1.0',
  349. 'Accept' => 'application/json',
  350. 'X-Foo' => ['Bar', 'Baz']
  351. ]
  352. ]);
  353. Headers may be added as default options when creating a client. When headers
  354. are used as default options, they are only applied if the request being created
  355. does not already contain the specific header. This includes both requests passed
  356. to the client in the ``send()`` and ``sendAsync()`` methods, and requests
  357. created by the client (e.g., ``request()`` and ``requestAsync()``).
  358. .. code-block:: php
  359. $client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);
  360. // Will send a request with the X-Foo header.
  361. $client->request('GET', '/get');
  362. // Sets the X-Foo header to "test", which prevents the default header
  363. // from being applied.
  364. $client->request('GET', '/get', ['headers' => ['X-Foo' => 'test']]);
  365. // Will disable adding in default headers.
  366. $client->request('GET', '/get', ['headers' => null]);
  367. // Will not overwrite the X-Foo header because it is in the message.
  368. use GuzzleHttp\Psr7\Request;
  369. $request = new Request('GET', 'http://foo.com', ['X-Foo' => 'test']);
  370. $client->send($request);
  371. // Will overwrite the X-Foo header with the request option provided in the
  372. // send method.
  373. use GuzzleHttp\Psr7\Request;
  374. $request = new Request('GET', 'http://foo.com', ['X-Foo' => 'test']);
  375. $client->send($request, ['headers' => ['X-Foo' => 'overwrite']]);
  376. .. _http-errors-option:
  377. http_errors
  378. -----------
  379. :Summary: Set to ``false`` to disable throwing exceptions on an HTTP protocol
  380. errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when
  381. HTTP protocol errors are encountered.
  382. :Types: bool
  383. :Default: ``true``
  384. :Constant: ``GuzzleHttp\RequestOptions::HTTP_ERRORS``
  385. .. code-block:: php
  386. $client->request('GET', '/status/500');
  387. // Throws a GuzzleHttp\Exception\ServerException
  388. $res = $client->request('GET', '/status/500', ['http_errors' => false]);
  389. echo $res->getStatusCode();
  390. // 500
  391. .. warning::
  392. This option only has an effect if your handler has the
  393. ``GuzzleHttp\Middleware::httpErrors`` middleware. This middleware is added
  394. by default when a client is created with no handler, and is added by
  395. default when creating a handler with ``GuzzleHttp\default_handler``.
  396. json
  397. ----
  398. :Summary: The ``json`` option is used to easily upload JSON encoded data as the
  399. body of a request. A Content-Type header of ``application/json`` will be
  400. added if no Content-Type header is already present on the message.
  401. :Types:
  402. Any PHP type that can be operated on by PHP's ``json_encode()`` function.
  403. :Default: None
  404. :Constant: ``GuzzleHttp\RequestOptions::JSON``
  405. .. code-block:: php
  406. $response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);
  407. Here's an example of using the ``tap`` middleware to see what request is sent
  408. over the wire.
  409. .. code-block:: php
  410. use GuzzleHttp\Middleware;
  411. // Grab the client's handler instance.
  412. $clientHandler = $client->getConfig('handler');
  413. // Create a middleware that echoes parts of the request.
  414. $tapMiddleware = Middleware::tap(function ($request) {
  415. echo $request->getHeaderLine('Content-Type');
  416. // application/json
  417. echo $request->getBody();
  418. // {"foo":"bar"}
  419. });
  420. $response = $client->request('PUT', '/put', [
  421. 'json' => ['foo' => 'bar'],
  422. 'handler' => $tapMiddleware($clientHandler)
  423. ]);
  424. .. note::
  425. This request option does not support customizing the Content-Type header
  426. or any of the options from PHP's `json_encode() <http://www.php.net/manual/en/function.json-encode.php>`_
  427. function. If you need to customize these settings, then you must pass the
  428. JSON encoded data into the request yourself using the ``body`` request
  429. option and you must specify the correct Content-Type header using the
  430. ``headers`` request option.
  431. This option cannot be used with ``body``, ``form_params``, or ``multipart``
  432. multipart
  433. ---------
  434. :Summary: Sets the body of the request to a `multipart/form-data` form.
  435. :Types: array
  436. :Constant: ``GuzzleHttp\RequestOptions::MULTIPART``
  437. The value of ``multipart`` is an array of associative arrays, each containing
  438. the following key value pairs:
  439. - ``name``: (string, required) the form field name
  440. - ``contents``: (StreamInterface/resource/string, required) The data to use in
  441. the form element.
  442. - ``headers``: (array) Optional associative array of custom headers to use with
  443. the form element.
  444. - ``filename``: (string) Optional string to send as the filename in the part.
  445. .. code-block:: php
  446. $client->request('POST', '/post', [
  447. 'multipart' => [
  448. [
  449. 'name' => 'foo',
  450. 'contents' => 'data',
  451. 'headers' => ['X-Baz' => 'bar']
  452. ],
  453. [
  454. 'name' => 'baz',
  455. 'contents' => fopen('/path/to/file', 'r')
  456. ],
  457. [
  458. 'name' => 'qux',
  459. 'contents' => fopen('/path/to/file', 'r'),
  460. 'filename' => 'custom_filename.txt'
  461. ],
  462. ]
  463. ]);
  464. .. note::
  465. ``multipart`` cannot be used with the ``form_params`` option. You will need to
  466. use one or the other. Use ``form_params`` for ``application/x-www-form-urlencoded``
  467. requests, and ``multipart`` for ``multipart/form-data`` requests.
  468. This option cannot be used with ``body``, ``form_params``, or ``json``
  469. .. _on-headers:
  470. on_headers
  471. ----------
  472. :Summary: A callable that is invoked when the HTTP headers of the response have
  473. been received but the body has not yet begun to download.
  474. :Types: - callable
  475. :Constant: ``GuzzleHttp\RequestOptions::ON_HEADERS``
  476. The callable accepts a ``Psr\Http\ResponseInterface`` object. If an exception
  477. is thrown by the callable, then the promise associated with the response will
  478. be rejected with a ``GuzzleHttp\Exception\RequestException`` that wraps the
  479. exception that was thrown.
  480. You may need to know what headers and status codes were received before data
  481. can be written to the sink.
  482. .. code-block:: php
  483. // Reject responses that are greater than 1024 bytes.
  484. $client->request('GET', 'http://httpbin.org/stream/1024', [
  485. 'on_headers' => function (ResponseInterface $response) {
  486. if ($response->getHeaderLine('Content-Length') > 1024) {
  487. throw new \Exception('The file is too big!');
  488. }
  489. }
  490. ]);
  491. .. note::
  492. When writing HTTP handlers, the ``on_headers`` function must be invoked
  493. before writing data to the body of the response.
  494. .. _on_stats:
  495. on_stats
  496. --------
  497. :Summary: ``on_stats`` allows you to get access to transfer statistics of a
  498. request and access the lower level transfer details of the handler
  499. associated with your client. ``on_stats`` is a callable that is invoked
  500. when a handler has finished sending a request. The callback is invoked
  501. with transfer statistics about the request, the response received, or the
  502. error encountered. Included in the data is the total amount of time taken
  503. to send the request.
  504. :Types: - callable
  505. :Constant: ``GuzzleHttp\RequestOptions::ON_STATS``
  506. The callable accepts a ``GuzzleHttp\TransferStats`` object.
  507. .. code-block:: php
  508. use GuzzleHttp\TransferStats;
  509. $client = new GuzzleHttp\Client();
  510. $client->request('GET', 'http://httpbin.org/stream/1024', [
  511. 'on_stats' => function (TransferStats $stats) {
  512. echo $stats->getEffectiveUri() . "\n";
  513. echo $stats->getTransferTime() . "\n";
  514. var_dump($stats->getHandlerStats());
  515. // You must check if a response was received before using the
  516. // response object.
  517. if ($stats->hasResponse()) {
  518. echo $stats->getResponse()->getStatusCode();
  519. } else {
  520. // Error data is handler specific. You will need to know what
  521. // type of error data your handler uses before using this
  522. // value.
  523. var_dump($stats->getHandlerErrorData());
  524. }
  525. }
  526. ]);
  527. progress
  528. --------
  529. :Summary: Defines a function to invoke when transfer progress is made.
  530. :Types: - callable
  531. :Default: None
  532. :Constant: ``GuzzleHttp\RequestOptions::PROGRESS``
  533. The function accepts the following positional arguments:
  534. - the total number of bytes expected to be downloaded
  535. - the number of bytes downloaded so far
  536. - the total number of bytes expected to be uploaded
  537. - the number of bytes uploaded so far
  538. .. code-block:: php
  539. // Send a GET request to /get?foo=bar
  540. $result = $client->request(
  541. 'GET',
  542. '/',
  543. [
  544. 'progress' => function(
  545. $downloadTotal,
  546. $downloadedBytes,
  547. $uploadTotal,
  548. $uploadedBytes
  549. ) {
  550. //do something
  551. },
  552. ]
  553. );
  554. .. _proxy-option:
  555. proxy
  556. -----
  557. :Summary: Pass a string to specify an HTTP proxy, or an array to specify
  558. different proxies for different protocols.
  559. :Types:
  560. - string
  561. - array
  562. :Default: None
  563. :Constant: ``GuzzleHttp\RequestOptions::PROXY``
  564. Pass a string to specify a proxy for all protocols.
  565. .. code-block:: php
  566. $client->request('GET', '/', ['proxy' => 'tcp://localhost:8125']);
  567. Pass an associative array to specify HTTP proxies for specific URI schemes
  568. (i.e., "http", "https"). Provide a ``no`` key value pair to provide a list of
  569. host names that should not be proxied to.
  570. .. note::
  571. Guzzle will automatically populate this value with your environment's
  572. ``NO_PROXY`` environment variable. However, when providing a ``proxy``
  573. request option, it is up to your to provide the ``no`` value parsed from
  574. the ``NO_PROXY`` environment variable
  575. (e.g., ``explode(',', getenv('NO_PROXY'))``).
  576. .. code-block:: php
  577. $client->request('GET', '/', [
  578. 'proxy' => [
  579. 'http' => 'tcp://localhost:8125', // Use this proxy with "http"
  580. 'https' => 'tcp://localhost:9124', // Use this proxy with "https",
  581. 'no' => ['.mit.edu', 'foo.com'] // Don't use a proxy with these
  582. ]
  583. ]);
  584. .. note::
  585. You can provide proxy URLs that contain a scheme, username, and password.
  586. For example, ``"http://username:password@192.168.16.1:10"``.
  587. query
  588. -----
  589. :Summary: Associative array of query string values or query string to add to
  590. the request.
  591. :Types:
  592. - array
  593. - string
  594. :Default: None
  595. :Constant: ``GuzzleHttp\RequestOptions::QUERY``
  596. .. code-block:: php
  597. // Send a GET request to /get?foo=bar
  598. $client->request('GET', '/get', ['query' => ['foo' => 'bar']]);
  599. Query strings specified in the ``query`` option will overwrite all query string
  600. values supplied in the URI of a request.
  601. .. code-block:: php
  602. // Send a GET request to /get?foo=bar
  603. $client->request('GET', '/get?abc=123', ['query' => ['foo' => 'bar']]);
  604. read_timeout
  605. ------------
  606. :Summary: Float describing the timeout to use when reading a streamed body
  607. :Types: float
  608. :Default: Defaults to the value of the ``default_socket_timeout`` PHP ini setting
  609. :Constant: ``GuzzleHttp\RequestOptions::READ_TIMEOUT``
  610. The timeout applies to individual read operations on a streamed body (when the ``stream`` option is enabled).
  611. .. code-block:: php
  612. $response = $client->request('GET', '/stream', [
  613. 'stream' => true,
  614. 'read_timeout' => 10,
  615. ]);
  616. $body = $response->getBody();
  617. // Returns false on timeout
  618. $data = $body->read(1024);
  619. // Returns false on timeout
  620. $line = fgets($body->detach());
  621. .. _sink-option:
  622. sink
  623. ----
  624. :Summary: Specify where the body of a response will be saved.
  625. :Types:
  626. - string (path to file on disk)
  627. - ``fopen()`` resource
  628. - ``Psr\Http\Message\StreamInterface``
  629. :Default: PHP temp stream
  630. :Constant: ``GuzzleHttp\RequestOptions::SINK``
  631. Pass a string to specify the path to a file that will store the contents of the
  632. response body:
  633. .. code-block:: php
  634. $client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
  635. Pass a resource returned from ``fopen()`` to write the response to a PHP stream:
  636. .. code-block:: php
  637. $resource = fopen('/path/to/file', 'w');
  638. $client->request('GET', '/stream/20', ['sink' => $resource]);
  639. Pass a ``Psr\Http\Message\StreamInterface`` object to stream the response
  640. body to an open PSR-7 stream.
  641. .. code-block:: php
  642. $resource = fopen('/path/to/file', 'w');
  643. $stream = GuzzleHttp\Psr7\stream_for($resource);
  644. $client->request('GET', '/stream/20', ['save_to' => $stream]);
  645. .. note::
  646. The ``save_to`` request option has been deprecated in favor of the
  647. ``sink`` request option. Providing the ``save_to`` option is now an alias
  648. of ``sink``.
  649. .. _ssl_key-option:
  650. ssl_key
  651. -------
  652. :Summary: Specify the path to a file containing a private SSL key in PEM
  653. format. If a password is required, then set to an array containing the path
  654. to the SSL key in the first array element followed by the password required
  655. for the certificate in the second element.
  656. :Types:
  657. - string
  658. - array
  659. :Default: None
  660. :Constant: ``GuzzleHttp\RequestOptions::SSL_KEY``
  661. .. note::
  662. ``ssl_key`` is implemented by HTTP handlers. This is currently only
  663. supported by the cURL handler, but might be supported by other third-part
  664. handlers.
  665. .. _stream-option:
  666. stream
  667. ------
  668. :Summary: Set to ``true`` to stream a response rather than download it all
  669. up-front.
  670. :Types: bool
  671. :Default: ``false``
  672. :Constant: ``GuzzleHttp\RequestOptions::STREAM``
  673. .. code-block:: php
  674. $response = $client->request('GET', '/stream/20', ['stream' => true]);
  675. // Read bytes off of the stream until the end of the stream is reached
  676. $body = $response->getBody();
  677. while (!$body->eof()) {
  678. echo $body->read(1024);
  679. }
  680. .. note::
  681. Streaming response support must be implemented by the HTTP handler used by
  682. a client. This option might not be supported by every HTTP handler, but the
  683. interface of the response object remains the same regardless of whether or
  684. not it is supported by the handler.
  685. synchronous
  686. -----------
  687. :Summary: Set to true to inform HTTP handlers that you intend on waiting on the
  688. response. This can be useful for optimizations.
  689. :Types: bool
  690. :Default: none
  691. :Constant: ``GuzzleHttp\RequestOptions::SYNCHRONOUS``
  692. .. _verify-option:
  693. verify
  694. ------
  695. :Summary: Describes the SSL certificate verification behavior of a request.
  696. - Set to ``true`` to enable SSL certificate verification and use the default
  697. CA bundle provided by operating system.
  698. - Set to ``false`` to disable certificate verification (this is insecure!).
  699. - Set to a string to provide the path to a CA bundle to enable verification
  700. using a custom certificate.
  701. :Types:
  702. - bool
  703. - string
  704. :Default: ``true``
  705. :Constant: ``GuzzleHttp\RequestOptions::VERIFY``
  706. .. code-block:: php
  707. // Use the system's CA bundle (this is the default setting)
  708. $client->request('GET', '/', ['verify' => true]);
  709. // Use a custom SSL certificate on disk.
  710. $client->request('GET', '/', ['verify' => '/path/to/cert.pem']);
  711. // Disable validation entirely (don't do this!).
  712. $client->request('GET', '/', ['verify' => false]);
  713. Not all system's have a known CA bundle on disk. For example, Windows and
  714. OS X do not have a single common location for CA bundles. When setting
  715. "verify" to ``true``, Guzzle will do its best to find the most appropriate
  716. CA bundle on your system. When using cURL or the PHP stream wrapper on PHP
  717. versions >= 5.6, this happens by default. When using the PHP stream
  718. wrapper on versions < 5.6, Guzzle tries to find your CA bundle in the
  719. following order:
  720. 1. Check if ``openssl.cafile`` is set in your php.ini file.
  721. 2. Check if ``curl.cainfo`` is set in your php.ini file.
  722. 3. Check if ``/etc/pki/tls/certs/ca-bundle.crt`` exists (Red Hat, CentOS,
  723. Fedora; provided by the ca-certificates package)
  724. 4. Check if ``/etc/ssl/certs/ca-certificates.crt`` exists (Ubuntu, Debian;
  725. provided by the ca-certificates package)
  726. 5. Check if ``/usr/local/share/certs/ca-root-nss.crt`` exists (FreeBSD;
  727. provided by the ca_root_nss package)
  728. 6. Check if ``/usr/local/etc/openssl/cert.pem`` (OS X; provided by homebrew)
  729. 7. Check if ``C:\windows\system32\curl-ca-bundle.crt`` exists (Windows)
  730. 8. Check if ``C:\windows\curl-ca-bundle.crt`` exists (Windows)
  731. The result of this lookup is cached in memory so that subsequent calls
  732. in the same process will return very quickly. However, when sending only
  733. a single request per-process in something like Apache, you should consider
  734. setting the ``openssl.cafile`` environment variable to the path on disk
  735. to the file so that this entire process is skipped.
  736. If you do not need a specific certificate bundle, then Mozilla provides a
  737. commonly used CA bundle which can be downloaded
  738. `here <https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt>`_
  739. (provided by the maintainer of cURL). Once you have a CA bundle available on
  740. disk, you can set the "openssl.cafile" PHP ini setting to point to the path to
  741. the file, allowing you to omit the "verify" request option. Much more detail on
  742. SSL certificates can be found on the
  743. `cURL website <http://curl.haxx.se/docs/sslcerts.html>`_.
  744. .. _timeout-option:
  745. timeout
  746. -------
  747. :Summary: Float describing the timeout of the request in seconds. Use ``0``
  748. to wait indefinitely (the default behavior).
  749. :Types: float
  750. :Default: ``0``
  751. :Constant: ``GuzzleHttp\RequestOptions::TIMEOUT``
  752. .. code-block:: php
  753. // Timeout if a server does not return a response in 3.14 seconds.
  754. $client->request('GET', '/delay/5', ['timeout' => 3.14]);
  755. // PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException'
  756. .. _version-option:
  757. version
  758. -------
  759. :Summary: Protocol version to use with the request.
  760. :Types: string, float
  761. :Default: ``1.1``
  762. :Constant: ``GuzzleHttp\RequestOptions::VERSION``
  763. .. code-block:: php
  764. // Force HTTP/1.0
  765. $request = $client->request('GET', '/get', ['version' => 1.0]);