5
Clients are used to create requests, create transactions, send requests
6
through an HTTP adapter, and return a response. You can add default request
7
options to a client that are applied to every request (e.g., default headers,
8
default query string parameters, etc.), and you can add event listeners and
9
subscribers to every request created by a client.
14
The constructor of a client accepts an associative array of configuration
18
Configures a base URL for the client so that requests created
19
using a relative URL are combined with the ``base_url`` of the client
20
according to section `5.2 of RFC 3986 <http://tools.ietf.org/html/rfc3986#section-5.2>`_.
24
// Create a client with a base URL
25
$client = new GuzzleHttp\Client(['base_url' => 'https://github.com']);
26
// Send a request to https://github.com/notifications
27
$response = $client->get('/notifications');
29
`Absolute URLs <http://tools.ietf.org/html/rfc3986#section-4.3>`_ sent
30
through a client will not use the base URL of the client.
33
Configures the HTTP adapter (``GuzzleHttp\Adapter\AdapterInterface``) used
34
to transfer the HTTP requests of a client. Guzzle will, by default, utilize
35
a stacked adapter that chooses the best adapter to use based on the provided
36
request options and based on the extensions available in the environment. If
37
cURL is installed, it will be used as the default adapter. However, if a
38
request has the ``stream`` request option, the PHP stream wrapper adapter
39
will be used (assuming ``allow_url_fopen`` is enabled in your PHP
43
Just like the ``adapter`` option, you can choose to specify an adapter
44
that is used to send requests in parallel
45
(``GuzzleHttp\Adapter\ParallelAdapterInterface``). Guzzle will by default
46
use cURL to send requests in parallel, but if cURL is not available it will
47
use the PHP stream wrapper and simply send requests serially.
50
Specifies the factory used to create HTTP requests and responses
51
(``GuzzleHttp\Message\MessageFactoryInterface``).
54
Associative array of :ref:`request-options` that are applied to every
55
request created by the client. This allows you to specify things like
56
default headers (e.g., User-Agent), default query string parameters, SSL
57
configurations, and any other supported request options.
60
Specifies an event emitter (``GuzzleHttp\Event\EmitterInterface``) instance
61
to be used by the client to emit request events. This option is useful if
62
you need to inject an emitter with listeners/subscribers already attached.
64
Here's an example of creating a client with various options, including using
65
a mock adapter that just returns the result of a callable function and a
66
base URL that is a URI template with parameters.
70
use GuzzleHttp\Client;
72
$client = new Client([
73
'base_url' => ['https://api.twitter.com/{version}/', ['version' => 'v1.1']],
75
'headers' => ['Foo' => 'Bar'],
76
'query' => ['testing' => '123'],
77
'auth' => ['username', 'password'],
78
'proxy' => 'tcp://localhost:80'
85
Requests can be created using various methods of a client. You can create
86
**and** send requests using one of the following methods:
88
- ``GuzzleHttp\Client::get``: Sends a GET request.
89
- ``GuzzleHttp\Client::head``: Sends a HEAD request
90
- ``GuzzleHttp\Client::post``: Sends a POST request
91
- ``GuzzleHttp\Client::put``: Sends a PUT request
92
- ``GuzzleHttp\Client::delete``: Sends a DELETE request
93
- ``GuzzleHttp\Client::options``: Sends an OPTIONS request
95
Each of the above methods accepts a URL as the first argument and an optional
96
associative array of :ref:`request-options` as the second argument.
100
$client = new GuzzleHttp\Client();
102
$client->put('http://httpbin.org', [
103
'headers' => ['X-Foo' => 'Bar'],
104
'body' => 'this is the body!',
105
'save_to' => '/path/to/local/file',
106
'allow_redirects' => false,
113
When a recoverable error is encountered while calling the ``send()`` method of
114
a client, a ``GuzzleHttp\Exception\RequestException`` is thrown.
118
use GuzzleHttp\Client;
119
use GuzzleHttp\Exception\RequestException;
121
$client = new Client();
124
$client->get('http://httpbin.org');
125
} catch (RequestException $e) {
126
echo $e->getRequest() . "\n";
127
if ($e->hasResponse()) {
128
echo $e->getResponse() . "\n";
132
``GuzzleHttp\Exception\RequestException`` always contains a
133
``GuzzleHttp\Message\RequestInterface`` object that can be accessed using the
134
exception's ``getRequest()`` method.
136
A response might be present in the exception. In the event of a networking
137
error, no response will be received. You can check if a ``RequestException``
138
has a response using the ``hasResponse()`` method. If the exception has a
139
response, then you can access the associated
140
``GuzzleHttp\Message\ResponseInterface`` using the ``getResponse()`` method of
146
If the ``exceptions`` request option is not set to ``false``, then exceptions
147
are thrown for HTTP protocol errors as well:
148
``GuzzleHttp\Exception\ClientErrorResponseException`` for 4xx level HTTP
149
responses and ``GuzzleHttp\Exception\ServerException`` for 5xx level responses,
150
both of which extend from ``GuzzleHttp\Exception\BadResponseException``.
155
You can create a request without sending it. This is useful for building up
156
requests over time or sending requests in parallel.
160
$request = $client->createRequest('GET', 'http://httpbin.org', [
161
'headers' => ['X-Foo' => 'Bar']
164
// Modify the request as needed
165
$request->setHeader('Baz', 'bar');
167
After creating a request, you can send it with the client's ``send()`` method.
171
$response = $client->send($request);
173
Sending Requests in Parallel
174
============================
176
You can send requests in parallel using a client object's ``sendAll()`` method.
177
The ``sendAll()`` method accepts an array or ``\Iterator`` that contains
178
``GuzzleHttp\Message\RequestInterface`` objects. In addition to providing the
179
requests to send, you can also specify an associative array of options that
180
will affect the transfer.
185
$client->createRequest('GET', 'http://httpbin.org'),
186
$client->createRequest('DELETE', 'http://httpbin.org/delete'),
187
$client->createRequest('PUT', 'http://httpbin.org/put', ['body' => 'test'])
190
$client->sendAll($requests);
192
The ``sendAll()`` method accepts the following associative array of options:
194
- **parallel**: Integer representing the maximum number of requests that are
195
allowed to be sent in parallel.
196
- **before**: Callable or array representing the event listeners to add to
197
each request's :ref:`before_event` event.
198
- **complete**: Callable or array representing the event listeners to add to
199
each request's :ref:`complete_event` event.
200
- **error**: Callable or array representing the event listeners to add to
201
each request's :ref:`error_event` event.
203
The "before", "complete", and "error" event options accept a callable or an
204
array of associative arrays where each associative array contains a "fn" key
205
with a callable value, an optional "priority" key representing the event
206
priority (with a default value of 0), and an optional "once" key that can be
207
set to true so that the event listener will be removed from the request after
208
it is first triggered.
212
use GuzzleHttp\Event\CompleteEvent;
214
// Add a single event listener using a callable.
215
$client->sendAll($requests, [
216
'complete' => function (CompleteEvent $event) {
217
echo 'Completed request to ' . $event->getRequest()->getUrl() . "\n";
218
echo 'Response: ' . $event->getResponse()->getBody() . "\n\n";
222
// The above is equivalent to the following, but the following structure
223
// allows you to add multiple event listeners to the same event name.
224
$client->sendAll($requests, [
227
'fn' => function (CompleteEvent $event) { /* ... */ },
228
'priority' => 0, // Optional
229
'once' => false // Optional
234
Asynchronous Response Handling
235
------------------------------
237
When sending requests in parallel, the request/response/error lifecycle must be
238
handled asynchronously. This means that you give the ``sendAll()`` method
239
multiple requests and handle the response or errors that is associated with the
240
request using event callbacks.
244
use GuzzleHttp\Event\ErrorEvent;
246
$client->sendAll($requests, [
247
'complete' => function (CompleteEvent $event) {
248
echo 'Completed request to ' . $event->getRequest()->getUrl() . "\n";
249
echo 'Response: ' . $event->getResponse()->getBody() . "\n\n";
250
// Do something with the completion of the request...
252
'error' => function (ErrorEvent $event) {
253
echo 'Request failed: ' . $event->getRequest()->getUrl() . "\n";
254
echo $event->getException();
255
// Do something to handle the error...
259
The ``GuzzleHttp\Event\ErrorEvent`` event object is emitted when an error
260
occurs during a transfer. With this event, you have access to the request that
261
was sent, the response that was received (if one was received), access to
262
transfer statistics, and the ability to intercept the exception with a
263
different ``GuzzleHttp\Message\ResponseInterface`` object. See :doc:`events`
264
for more information.
266
Handling Errors After Transferring
267
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
269
It sometimes might be easier to handle all of the errors that occurred during a
270
transfer after all of the requests have been sent. Here we are adding each
271
failed request to an array that we can use to process errors later.
275
use GuzzleHttp\Event\ErrorEvent;
278
$client->sendAll($requests, [
279
'error' => function (ErrorEvent $event) use (&$errors) {
284
foreach ($errors as $error) {
285
// Handle the error...
288
Throwing Errors Immediately
289
~~~~~~~~~~~~~~~~~~~~~~~~~~~
291
It sometimes is useful to throw exceptions immediately when they occur. The
292
following example shows how to use an event listener to throw exceptions
293
immediately and prevent subsequent requests from being sent.
297
use GuzzleHttp\Event\ErrorEvent;
299
$client->sendAll($requests, [
300
'error' => function (ErrorEvent $event) {
301
$event->throwImmediately(true);
305
Calling the ``ErrorEvent::throwImmediately()`` instructs the
306
``ParallelAdapterInterface`` sending the request to stop sending subsequent
307
requests, clean up any opened resources, and throw the exception associated
308
with the event as soon as possible. If the error event was not sent by a
309
``ParallelAdapterInterface``, then calling ``throwImmediately()`` has no
314
Subsequent listeners of the "error" event can still intercept the error
315
event with a response if needed, which will, as per the standard behavior,
316
prevent the exception from being thrown.
323
Sometimes you just want to send a few requests in parallel and then process
324
the results all at once after they've been sent. Guzzle provides a convenience
325
function ``GuzzleHttp\batch()`` that makes this very simple:
329
$client = new GuzzleHttp\Client();
332
$client->createRequest('GET', 'http://httpbin.org/get'),
333
$client->createRequest('HEAD', 'http://httpbin.org/get'),
334
$client->createRequest('PUT', 'http://httpbin.org/put'),
337
$results = GuzzleHttp\batch($client, $requests);
339
// Results is an SplObjectStorage object where each request is a key
340
foreach ($requests as $request) {
341
echo $request->getUrl() . "\n";
342
// Get the result (either a ResponseInterface or RequestException)
343
$result = $results[$request];
344
if ($result instanceof ResponseInterface) {
345
// Interact with the response directly
346
echo $result->getStatusCode();
348
// Get the exception message
349
echo $result->getMessage();
353
``GuzzleHttp\batch()`` accepts an optional associative array of options in the
354
third argument that allows you to specify the 'before', 'complete' and 'error'
355
events as well as specify the maximum number of requests to send in parallel
356
using the 'parallel' option key. This options array is the exact same format as
357
the options array exposed in ``GuzzleHttp\ClientInterface::sendAll()``.
364
You can customize requests created by a client using **request options**.
365
Request options control various aspects of a request including, headers,
366
query string parameters, timeout settings, the body of a request, and much
369
All of the following examples use the following client:
373
$client = new GuzzleHttp\Client(['base_url' => 'http://httpbin.org']);
378
:Summary: Associative array of headers to add to the request. Each key is the
379
name of a header, and each value is a string or array of strings
380
representing the header field values.
386
// Set various headers on a request
387
$client->get('/get', [
389
'User-Agent' => 'testing/1.0',
390
'Accept' => 'application/json',
391
'X-Foo' => ['Bar', 'Baz']
398
:Summary: The ``body`` option is used to control the body of an entity
399
enclosing request (e.g., PUT, POST, PATCH).
402
- ``fopen()`` resource
403
- ``GuzzleHttp\Stream\StreamInterface``
404
- ``GuzzleHttp\Post\PostBodyInterface``
407
This setting can be set to any of the following types:
413
// You can send requests that use a string as the message body.
414
$client->put('/put', ['body' => 'foo']);
416
- resource returned from ``fopen()``
420
// You can send requests that use a stream resource as the body.
421
$resource = fopen('http://httpbin.org', 'r');
422
$client->put('/put', ['body' => $resource]);
426
Use an array to send POST style requests that use a
427
``GuzzleHttp\Post\PostBodyInterface`` object as the body.
431
// You can send requests that use a POST body containing fields & files.
432
$client->post('/post', [
435
'other_field' => '123',
436
'file_name' => fopen('/path/to/file', 'r')
440
- ``GuzzleHttp\Stream\StreamInterface``
444
// You can send requests that use a Guzzle stream object as the body
445
$stream = GuzzleHttp\Stream\Stream::factory('contents...');
446
$client->post('/post', ['body' => $stream]);
451
:Summary: The ``json`` option is used to easily upload JSON encoded data as the
452
body of a request. A Content-Type header of ``application/json`` will be
453
added if no Content-Type header is already present on the message.
455
Any PHP type that can be operated on by PHP's ``json_encode()`` function.
460
$request = $client->createRequest('/put', ['json' => ['foo' => 'bar']]);
461
echo $request->getHeader('Content-Type');
463
echo $request->getBody();
468
This request option does not support customizing the Content-Type header
469
or any of the options from PHP's `json_encode() <http://www.php.net/manual/en/function.json-encode.php>`_
470
function. If you need to customize these settings, then you must pass the
471
JSON encoded data into the request yourself using the ``body`` request
472
option and you must specify the correct Content-Type header using the
473
``headers`` request option.
478
:Summary: Associative array of query string values to add to the request.
481
- ``GuzzleHttp\Query``
486
// Send a GET request to /get?foo=bar
487
$client->get('/get', ['query' => ['foo' => 'bar']]);
489
Query strings specified in the ``query`` option are combined with any query
490
string values that are parsed from the URL.
494
// Send a GET request to /get?abc=123&foo=bar
495
$client->get('/get?abc=123', ['query' => ['foo' => 'bar']]);
500
:Summary: Pass an array of HTTP authentication parameters to use with the
501
request. The array must contain the username in index [0], the password in
502
index [1], and you can optionally provide a built-in authentication type in
503
index [2]. Pass ``null`` to disable authentication for a request.
510
The built-in authentication types are as follows:
513
Use `basic HTTP authentication <http://www.ietf.org/rfc/rfc2069.txt>`_ in
514
the ``Authorization`` header (the default setting used if none is
519
$client->get('/get', ['auth' => ['username', 'password']]);
522
Use `digest authentication <http://www.ietf.org/rfc/rfc2069.txt>`_ (must be
523
supported by the HTTP adapter).
527
$client->get('/get', ['auth' => ['username', 'password', 'digest']]);
529
*This is currently only supported when using the cURL adapter, but creating
530
a replacement that can be used with any HTTP adapter is planned.*
534
The authentication type (whether it's provided as a string or as the third
535
option in an array) is always converted to a lowercase string. Take this
536
into account when implementing custom authentication types and when
537
implementing custom message factories.
539
Custom Authentication Schemes
540
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
542
You can also provide a string representing a custom authentication type name.
543
When using a custom authentication type string, you will need to implement
544
the authentication method in an event listener that checks the ``auth`` request
545
option of a request before it is sent. Authentication listeners that require
546
a request is not modified after they are signed should have a very low priority
547
to ensure that they are fired last or near last in the event chain.
551
use GuzzleHttp\Event\BeforeEvent;
552
use GuzzleHttp\Event\RequestEvents;
555
* Custom authentication listener that handles the "foo" auth type.
557
* Listens to the "before" event of a request and only modifies the request
558
* when the "auth" config setting of the request is "foo".
560
class FooAuth implements GuzzleHttp\Event\SubscriberInterface
564
public function __construct($password)
566
$this->password = $password;
569
public function getEvents()
571
return ['before' => ['sign', RequestEvents::SIGN_REQUEST]];
574
public function sign(BeforeEvent $e)
576
if ($e->getRequest()->getConfig()['auth'] == 'foo') {
577
$e->getRequest()->setHeader('X-Foo', 'Foo ' . $this->password);
582
$client->getEmitter()->attach(new FooAuth('password'));
583
$client->get('/', ['auth' => 'foo']);
585
Adapter Specific Authentication Schemes
586
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
588
If you need to use authentication methods provided by cURL (e.g., NTLM, GSS,
589
etc.), then you need to specify a curl adapter option in the ``options``
590
request option array. See :ref:`config-option` for more information.
597
:Summary: Specifies whether or not cookies are used in a request or what cookie
598
jar to use or what cookies to send.
602
- ``GuzzleHttp\Cookie\CookieJarInterface``
605
Set to ``true`` to use a shared cookie session associated with the client.
609
// Enable cookies using the shared cookie jar of the client.
610
$client->get('/get', ['cookies' => true]);
612
Pass an associative array containing cookies to send in the request and start a
617
// Enable cookies and send specific cookies
618
$client->get('/get', ['cookies' => ['foo' => 'bar']]);
620
Set to a ``GuzzleHttp\Cookie\CookieJarInterface`` object to use an existing
625
$jar = new GuzzleHttp\Cookie\CookieJar();
626
$client->get('/get', ['cookies' => $jar]);
628
.. _allow_redirects-option:
633
:Summary: Describes the redirect behavior of a request
637
:Default: ``['max' => 5, 'strict' => false, 'referer' => true]``
639
Set to ``false`` to disable redirects.
643
$res = $client->get('/redirect/3', ['allow_redirects' => false]);
644
echo $res->getStatusCode();
647
Set to ``true`` (the default setting) to enable normal redirects with a maximum
648
number of 5 redirects.
652
$res = $client->get('/redirect/3');
653
echo $res->getStatusCode();
656
Pass an associative array containing the 'max' key to specify the maximum
657
number of redirects, optionally provide a 'strict' key value to specify
658
whether or not to use strict RFC compliant redirects (meaning redirect POST
659
requests with POST requests vs. doing what most browsers do which is redirect
660
POST requests with GET requests), and optionally provide a 'referer' key to
661
specify whether or not the "Referer" header should be added when redirecting.
665
$res = $client->get('/redirect/3', [
666
'allow_redirects' => [
672
echo $res->getStatusCode();
678
:Summary: Specify whether or not ``Content-Encoding`` responses (gzip,
679
deflate, etc.) are automatically decoded.
685
This option can be used to control how content-encoded response bodies are
686
handled. By default, ``decode_content`` is set to true, meaning any gzipped
687
or deflated response will be decoded by Guzzle.
689
When set to ``false``, the body of a response is never decoded, meaning the
690
bytes pass through the adapter unchanged.
694
// Request gzipped data, but do not decode it while downloading
695
$client->get('/foo.js', [
696
'headers' => ['Accept-Encoding' => 'gzip'],
697
'decode_content' => false
700
When set to a string, the bytes of a response are decoded and the string value
701
provided to the ``decode_content`` option is passed as the ``Accept-Encoding``
702
header of the request.
706
// Pass "gzip" as the Accept-Encoding header.
707
$client->get('/foo.js', ['decode_content' => 'gzip']);
714
:Summary: Specify where the body of a response will be saved.
717
- ``fopen()`` resource
718
- ``GuzzleHttp\Stream\StreamInterface``
719
:Default: PHP temp stream
721
Pass a string to specify the path to a file that will store the contents of the
726
$client->get('/stream/20', ['save_to' => '/path/to/file']);
728
Pass a resource returned from ``fopen()`` to write the response to a PHP stream:
732
$resource = fopen('/path/to/file', 'w');
733
$client->get('/stream/20', ['save_to' => $resource]);
735
Pass a ``GuzzleHttp\Stream\StreamInterface`` object to stream the response body
736
to an open Guzzle stream:
740
$resource = fopen('/path/to/file', 'w');
741
$stream = GuzzleHttp\Stream\Stream::factory($resource);
742
$client->get('/stream/20', ['save_to' => $stream]);
749
:Summary: An associative array mapping event names to a callable. Or an
750
associative array containing the 'fn' key that maps to a callable, an
751
optional 'priority' key used to specify the event priority, and an optional
752
'once' key used to specify if the event should remove itself the first time
759
use GuzzleHttp\Event\BeforeEvent;
760
use GuzzleHttp\Event\HeadersEvent;
761
use GuzzleHttp\Event\CompleteEvent;
762
use GuzzleHttp\Event\ErrorEvent;
766
'before' => function (BeforeEvent $e) { echo 'Before'; },
767
'headers' => function (HeadersEvent $e) { echo 'Headers'; },
768
'complete' => function (CompleteEvent $e) { echo 'Complete'; },
769
'error' => function (ErrorEvent $e) { echo 'Error'; },
773
Here's an example of using the associative array format for control over the
774
priority and whether or not an event should be triggered more than once.
781
'fn' => function (BeforeEvent $e) { echo 'Before'; },
788
.. _subscribers-option:
793
:Summary: Array of event subscribers to add to the request. Each value in the
794
array must be an instance of ``GuzzleHttp\Event\SubscriberInterface``.
800
use GuzzleHttp\Subscriber\History;
801
use GuzzleHttp\Subscriber\Mock;
802
use GuzzleHttp\Message\Response;
804
$history = new History();
805
$mock = new Mock([new Response(200)]);
806
$client->get('/', ['subscribers' => [$history, $mock]]);
809
// Outputs the request and response history
811
.. _exceptions-option:
816
:Summary: Set to ``false`` to disable throwing exceptions on an HTTP protocol
817
errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when
818
HTTP protocol errors are encountered.
824
$client->get('/status/500');
825
// Throws a GuzzleHttp\Exception\ServerException
827
$res = $client->get('/status/500', ['exceptions' => false]);
828
echo $res->getStatusCode();
836
:Summary: Float describing the timeout of the request in seconds. Use ``0``
837
to wait indefinitely (the default behavior).
843
// Timeout if a server does not return a response in 3.14 seconds.
844
$client->get('/delay/5', ['timeout' => 3.14]);
845
// PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException'
847
.. _connect_timeout-option:
852
:Summary: Float describing the number of seconds to wait while trying to connect
853
to a server. Use ``0`` to wait indefinitely (the default behavior).
859
// Timeout if the client fails to connect to the server in 3.14 seconds.
860
$client->get('/delay/5', ['connect_timeout' => 3.14]);
864
This setting must be supported by the HTTP adapter used to send a request.
865
``connect_timeout`` is currently only supported by the built-in cURL
873
:Summary: Describes the SSL certificate verification behavior of a request.
874
Set to ``true`` to enable SSL certificate verification (the default). Set
875
to ``false`` to disable certificate verification (this is insecure!). Set
876
to a string to provide the path to a CA bundle to enable verification using
877
a custom certificate.
885
// Use a custom SSL certificate
886
$client->get('/', ['verify' => '/path/to/cert.pem']);
888
// Disable validation
889
$client->get('/', ['verify' => false]);
896
:Summary: Set to a string to specify the path to a file containing a PEM
897
formatted client side certificate. If a password is required, then set to
898
an array containing the path to the PEM file in the first array element
899
followed by the password required for the certificate in the second array
908
$client->get('/', ['cert' => ['/path/server.pem', 'password']]);
915
:Summary: Specify the path to a file containing a private SSL key in PEM
916
format. If a password is required, then set to an array containing the path
917
to the SSL key in the first array element followed by the password required
918
for the certificate in the second element.
926
``ssl_key`` is implemented by HTTP adapters. This is currently only
927
supported by the cURL adapter, but might be supported by other third-part
935
:Summary: Pass a string to specify an HTTP proxy, or an array to specify
936
different proxies for different protocols.
942
Pass a string to specify a proxy for all protocols.
946
$client->get('/', ['proxy' => 'tcp://localhost:8125']);
948
Pass an associative array to specify HTTP proxies for specific URI schemes
949
(i.e., "http", "https").
955
'http' => 'tcp://localhost:8125', // Use this proxy with "http"
956
'https' => 'tcp://localhost:9124' // Use this proxy with "https"
962
You can provide proxy URLs that contain a scheme, username, and password.
963
For example, ``"http://username:password@192.168.16.1:10"``.
970
:Summary: Set to ``true`` or set to a PHP stream returned by ``fopen()`` to
971
enable debug output with the adapter used to send a request. For example,
972
when using cURL to transfer requests, cURL's verbose of ``CURLOPT_VERBOSE``
973
will be emitted. When using the PHP stream wrapper, stream wrapper
974
notifications will be emitted. If set to true, the output is written to
975
PHP's STDOUT. If a PHP stream is provided, output is written to the stream.
978
- ``fopen()`` resource
983
$client->get('/get', ['debug' => true]);
985
Running the above example would output something like the following:
989
* About to connect() to httpbin.org port 80 (#0)
990
* Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0)
993
User-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7
996
< Access-Control-Allow-Origin: *
997
< Content-Type: application/json
998
< Date: Sun, 16 Feb 2014 06:50:09 GMT
999
< Server: gunicorn/0.17.4
1000
< Content-Length: 335
1001
< Connection: keep-alive
1003
* Connection #0 to host httpbin.org left intact
1010
:Summary: Set to ``true`` to stream a response rather than download it all
1017
$response = $client->get('/stream/20', ['stream' => true]);
1018
// Read bytes off of the stream until the end of the stream is reached
1019
$body = $response->getBody();
1020
while (!$body->eof()) {
1021
echo $body->read(1024);
1026
Streaming response support must be implemented by the HTTP adapter used by
1027
a client. This option might not be supported by every HTTP adapter, but the
1028
interface of the response object remains the same regardless of whether or
1029
not it is supported by the adapter.
1036
:Summary: Controls the behavior of the "Expect: 100-Continue" header.
1040
:Default: ``1048576``
1042
Set to ``true`` to enable the "Expect: 100-Continue" header for all requests
1043
that sends a body. Set to ``false`` to disable the "Expect: 100-Continue"
1044
header for all requests. Set to a number so that the size of the payload must
1045
be greater than the number in order to send the Expect header. Setting to a
1046
number will send the Expect header for all requests in which the size of the
1047
payload cannot be determined or where the body is not rewindable.
1049
By default, Guzzle will add the "Expect: 100-Continue" header when the size of
1050
the body of a request is greater than 1 MB and a request is using HTTP/1.1.
1054
This option only takes effect when using HTTP/1.1. The HTTP/1.0 and
1055
HTTP/2.0 protocols do not support the "Expect: 100-Continue" header.
1056
Support for handling the "Expect: 100-Continue" workflow must be
1057
implemented by Guzzle HTTP adapters used by a client.
1064
:Summary: Protocol version to use with the request.
1065
:Types: string, float
1071
$request = $client->createRequest('GET', '/get', ['version' => 1.0]);
1072
echo $request->getProtocolVersion();
1080
:Summary: Associative array of config options that are forwarded to a request's
1081
configuration collection. These values are used as configuration options
1082
that can be consumed by plugins and adapters.
1088
$request = $client->createRequest('GET', '/get', ['config' => ['foo' => 'bar']]);
1089
echo $request->getConfig('foo');
1092
Some HTTP adapters allow you to specify custom adapter-specific settings. For
1093
example, you can pass custom cURL options to requests by passing an associative
1094
array in the ``config`` request option under the ``curl`` key.
1098
// Use custom cURL options with the request. This example uses NTLM auth
1099
// to authenticate with a server.
1103
CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
1104
CURLOPT_USERPWD => 'username:password'
1112
Requests emit lifecycle events when they are transferred. A client object has a
1113
``GuzzleHttp\Common\EventEmitter`` object that can be used to add event
1114
*listeners* and event *subscribers* to all requests created by the client.
1118
**Every** event listener or subscriber added to a client will be added to
1119
every request created by the client.
1123
use GuzzleHttp\Client;
1124
use GuzzleHttp\Event\BeforeEvent;
1126
$client = new Client();
1128
// Add a listener that will echo out requests before they are sent
1129
$client->getEmitter()->on('before', function (BeforeEvent $e) {
1130
echo 'About to send request: ' . $e->getRequest();
1133
$client->get('http://httpbin.org/get');
1134
// Outputs the request as a string because of the event
1136
See :doc:`events` for more information on the event system used in Guzzle.
1138
Environment Variables
1139
=====================
1141
Guzzle exposes a few environment variables that can be used to customize the
1142
behavior of the library.
1144
``GUZZLE_CURL_SELECT_TIMEOUT``
1145
Controls the duration in seconds that ``GuzzleHttp\Adapter\Curl\MultiAdapter``
1146
will use when selecting handles using ``curl_multi_select()``. Some systems
1147
have issues with PHP's implementation of ``curl_multi_select()`` where
1148
calling this function always results in waiting for the maximum duration of
1151
Defines the proxy to use when sending requests using the "http" protocol.
1153
Defines the proxy to use when sending requests using the "https" protocol.
1155
Relevant ini Settings
1156
---------------------
1158
Guzzle can utilize PHP ini settings when configuring clients.
1161
Specifies the path on disk to a CA file in PEM format to use when sending
1162
requests over "https". See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults