request-options.rst 32 KB

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