### Pass 'gzip' as Accept-Encoding header Source: https://docs.guzzlephp.org/en/stable/request-options.html Sets 'decode_content' to a string, which is passed as the 'Accept-Encoding' header. The example sends a GET request to '/foo.js' with 'decode_content' set to 'gzip'. ```php // Pass "gzip" as the Accept-Encoding header. $client->request('GET', '/foo.js', ['decode_content' => 'gzip']); ``` -------------------------------- ### Sample debug output from cURL verbose Source: https://docs.guzzlephp.org/en/stable/request-options.html Example output from running the debug example, showing cURL verbose messages including connection details and HTTP request/response headers. ```text * About to connect() to httpbin.org port 80 (#0) * Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0) > GET /get HTTP/1.1 Host: httpbin.org User-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7 < HTTP/1.1 200 OK < Access-Control-Allow-Origin: * < Content-Type: application/json < Date: Sun, 16 Feb 2014 06:50:09 GMT < Server: gunicorn/0.17.4 < Content-Length: 335 < Connection: keep-alive < * Connection #0 to host httpbin.org left intact ``` -------------------------------- ### Clone Guzzle and install dependencies Source: https://docs.guzzlephp.org/en/stable/overview.html Commands to clone the Guzzle repository from GitHub and install its dependencies using Composer. ```bash git clone https://github.com/guzzle/guzzle.git cd guzzle && composer install ``` -------------------------------- ### Install Composer Source: https://docs.guzzlephp.org/en/stable/overview.html Command to install Composer, the dependency manager used to install Guzzle. ```bash # Install Composer curl -sS https://getcomposer.org/installer | php ``` -------------------------------- ### Access response start-line: status code, reason phrase, protocol version Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to retrieve the status code, reason phrase, and protocol version from a Guzzle response object. The example uses a GET request to httpbin.org and echoes the values. ```php $client = new \GuzzleHttp\Client(); $response = $client->request('GET', 'http://httpbin.org/get'); echo $response->getStatusCode(); // 200 echo $response->getReasonPhrase(); // OK echo $response->getProtocolVersion(); // 1.1 ``` -------------------------------- ### Enable debug output with 'debug' => true Source: https://docs.guzzlephp.org/en/stable/request-options.html Sets the 'debug' option to true to enable verbose output, written to PHP's STDOUT. The example shows a GET request to '/get' with the debug option enabled. ```php $client->request('GET', '/get', ['debug' => true]); ``` -------------------------------- ### Create a stream from a string with Utils::streamFor Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to create a PSR-7 stream from a string using GuzzleHttp\Psr7\Utils::streamFor. The example demonstrates reading, getting contents, checking eof, and tell. ```php use GuzzleHttp\Psr7; $stream = Psr7\Utils::streamFor('string data'); echo $stream; // string data echo $stream->read(3); // str echo $stream->getContents(); // ing data var_export($stream->eof()); // true var_export($stream->tell()); // 11 ``` -------------------------------- ### IDN conversion request example Source: https://docs.guzzlephp.org/en/stable/request-options.html Enables Internationalized Domain Name (IDN) support, which is on by default when the intl extension is available. The example requests https://яндекс.рф and notes that the domain is translated to its punycode form xn--d1acufc.xn--p1ai. ```php $client->request('GET', 'https://яндекс.рф'); // яндекс.рф is translated to xn--d1acufc.xn--p1ai ``` -------------------------------- ### Create a Guzzle client with base_uri Source: https://docs.guzzlephp.org/en/stable/request-options.html Sets up a Guzzle client with a base URI for all requests. Used as the foundation for the examples on this page. ```php $client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org']); ``` -------------------------------- ### Specify Guzzle in composer.json Source: https://docs.guzzlephp.org/en/stable/overview.html Alternative installation method: add the guzzlehttp/guzzle requirement to the project's composer.json file. ```json { "require": { "guzzlehttp/guzzle": "^7.0" } } ``` -------------------------------- ### Create a PSR-7 request with GuzzleHttp\Psr7\Request Source: https://docs.guzzlephp.org/en/stable/psr7.html Use the Request class to create an HTTP request. The constructor requires a method and URI; optional arguments include headers and body. The example shows a GET request and a PUT request with custom headers and body. ```php use GuzzleHttp\Psr7\Request; $request = new Request('GET', 'http://httpbin.org/get'); // You can provide other optional constructor arguments. $headers = ['X-Foo' => 'Bar']; $body = 'hello!'; $request = new Request('PUT', 'http://httpbin.org/put', $headers, $body); ``` -------------------------------- ### Queue a response on the test server Source: https://docs.guzzlephp.org/en/stable/testing.html Use GuzzleHttp\Tests\Server::enqueue to queue a response. The server starts automatically and waits until it can receive requests. Create a client with the server's URL as base_uri and send a request to get the queued response. ```php use GuzzleHttp\Client; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Tests\Server; // Start the server and queue a response Server::enqueue([ new Response(200, ['Content-Length' => 0]) ]); $client = new Client(['base_uri' => Server::$url]); echo $client->request('GET', '/foo')->getStatusCode(); // 200 ``` -------------------------------- ### Basic Guzzle Client Request and Async Request Source: https://docs.guzzlephp.org/en/stable?__cf_chl_rt_tk=y0Iiq_3OL.E_5XyG8mzNfgHLxM2hBqa0TBOIm37Tqyk-1787737915-1.0.1.1-AGU89S7YRaodjRkOKxCSs.xo0343N1yoXQCeQLAE01g Shows how to create a Guzzle client, send a synchronous GET request with basic authentication, and send an asynchronous request using a promise. The synchronous request outputs the status code, content-type header, and body. The async request uses sendAsync and then waits for the promise to complete. ```php $client = new GuzzleHttp\Client(); $res = $client->request('GET', 'https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // "200" echo $res->getHeader('content-type')[0]; // 'application/json; charset=utf8' echo $res->getBody(); // {"type":"User"...' // Send an asynchronous request. $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); $promise = $client->sendAsync($request)->then(function ($response) { echo 'I completed! ' . $response->getBody(); }); $promise->wait(); ``` -------------------------------- ### Access request host Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to get the host from the URI and the Host header. ```php $request = new Request('GET', 'http://httpbin.org'); echo $request->getUri()->getHost(); // httpbin.org echo $request->getHeader('Host'); // httpbin.org ``` -------------------------------- ### Send GET request with query option Source: https://docs.guzzlephp.org/en/stable/request-options.html Sends a GET request to /get with the query parameter foo=bar using the 'query' request option. The query option accepts an associative array of query string values. ```php // Send a GET request to /get?foo=bar $client->request('GET', '/get', ['query' => ['foo' => 'bar']]); ``` -------------------------------- ### Send asynchronous request with requestAsync and then Source: https://docs.guzzlephp.org/en/stable/faq.html Use the requestAsync method to send an asynchronous GET request. The returned promise allows chaining a then callback to handle the response. The example echoes the status code when the response is received. ```php $promise = $client->requestAsync('GET', 'http://httpbin.org/get'); $promise->then(function ($response) { echo 'Got a response! ' . $response->getStatusCode(); }); ``` -------------------------------- ### Create a stream from an iterator with Utils::streamFor Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to create a stream from a generator that yields bytes. The example reads 3 bytes from a 1024-byte stream. ```php use GuzzleHttp\Psr7; $generator = function ($bytes) { for ($i = 0; $i < $bytes; $i++) { yield '.'; } }; $iter = $generator(1024); $stream = Psr7\Utils::streamFor($iter); echo $stream->read(3); // ... ``` -------------------------------- ### Access request path Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to get the path from a request URI using getPath(). ```php $request = new Request('GET', 'http://httpbin.org/get'); echo $request->getUri()->getPath(); // /get ``` -------------------------------- ### Send PATCH request with body Source: https://docs.guzzlephp.org/en/stable/psr7.html Example of sending a PATCH request using the client's patch() method with a body option. ```php $response = $client->patch('http://httpbin.org/patch', ['body' => 'content']); ``` -------------------------------- ### Iterate over headers with getHeaders() Source: https://docs.guzzlephp.org/en/stable/psr7.html Use getHeaders() to iterate over all headers of a message. The example prints each header name and its values joined by commas. ```php foreach ($request->getHeaders() as $name => $values) { echo $name . ': ' . implode(', ', $values) . "\r\n"; } ``` -------------------------------- ### Example of a complex Link header Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows a Link header that contains a link and additional key-value pairs, demonstrating the format that Guzzle's Header::parse() can parse. ```http ; rel="thing"; type="image/jpeg" ``` -------------------------------- ### Send synchronous requests with magic methods Source: https://docs.guzzlephp.org/en/stable/quickstart.html Magic methods on the client send synchronous requests for each HTTP verb: get, delete, head, options, patch, post, and put. ```php $response = $client->get('http://httpbin.org/get'); $response = $client->delete('http://httpbin.org/delete'); $response = $client->head('http://httpbin.org/get'); $response = $client->options('http://httpbin.org/get'); $response = $client->patch('http://httpbin.org/patch'); $response = $client->post('http://httpbin.org/post'); $response = $client->put('http://httpbin.org/put'); ``` -------------------------------- ### Get a cookie by name with getCookieByName Source: https://docs.guzzlephp.org/en/stable/quickstart.html Get a cookie by its name with the getCookieByName($name) method, which returns a GuzzleHttp\Cookie\SetCookie instance. The example shows how to retrieve the cookie's value, domain, and expiration date. ```php $cookie = $jar->getCookieByName('some_cookie'); $cookie->getValue(); // 'foo' $cookie->getDomain(); // 'example.org' $cookie->getExpires(); // expiration date as a Unix timestamp ``` -------------------------------- ### Create and use a handler stack with push and unshift Source: https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html Creates a HandlerStack, sets a base handler, pushes three middleware that echo 'A', 'B', 'C', then unshifts one that echoes '0'. The client request outputs 'ABC' before unshift and '0ABC' after. ```php use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Utils; use Psr\Http\Message\RequestInterface; $stack = new HandlerStack(); $stack->setHandler(Utils::chooseHandler()); $stack->push(Middleware::mapRequest(function (RequestInterface $r) { echo 'A'; return $r; })); $stack->push(Middleware::mapRequest(function (RequestInterface $r) { echo 'B'; return $r; })); $stack->push(Middleware::mapRequest(function (RequestInterface $r) { echo 'C'; return $r; })); $client->request('GET', 'http://httpbin.org/'); // echoes 'ABC'; $stack->unshift(Middleware::mapRequest(function (RequestInterface $r) { echo '0'; return $r; })); $client = new Client(['handler' => $stack]); $client->request('GET', 'http://httpbin.org/'); // echoes '0ABC'; ``` -------------------------------- ### Name middleware and use before, after, and remove Source: https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html Shows how to name middleware for targeted insertion. Uses before() to add before a named middleware, after() to add after, and remove() to delete by name. ```php use Psr\Http\Message\RequestInterface; use GuzzleHttp\Middleware; // Add a middleware with a name $stack->push(Middleware::mapRequest(function (RequestInterface $r) { return $r->withHeader('X-Foo', 'Bar'); }, 'add_foo')); // Add a middleware before a named middleware (unshift before). $stack->before('add_foo', Middleware::mapRequest(function (RequestInterface $r) { return $r->withHeader('X-Baz', 'Qux'); }, 'add_baz')); // Add a middleware after a named middleware (pushed after). $stack->after('add_baz', Middleware::mapRequest(function (RequestInterface $r) { return $r->withHeader('X-Lorem', 'Ipsum'); })); // Remove a middleware by name $stack->remove('add_foo'); ``` -------------------------------- ### Request gzipped data without decoding Source: https://docs.guzzlephp.org/en/stable/request-options.html Sets 'decode_content' to false to prevent automatic decoding of gzipped responses. The example sends a GET request to '/foo.js' with an 'Accept-Encoding' header of 'gzip' and 'decode_content' set to false. ```php // Request gzipped data, but do not decode it while downloading $client->request('GET', '/foo.js', [ 'headers' => ['Accept-Encoding' => 'gzip'], 'decode_content' => false ]); ``` -------------------------------- ### Create a Guzzle client with base_uri and timeout Source: https://docs.guzzlephp.org/en/stable/quickstart.html Creates a Guzzle client with a base URI and default timeout. The client is immutable, so defaults cannot be changed after creation. ```php use GuzzleHttp\Client; $client = new Client([ // Base URI is used with relative requests 'base_uri' => 'http://httpbin.org', // You can set any number of default request options. 'timeout' => 2.0, ]); ``` -------------------------------- ### Create request with query string Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to create a request with a URI containing a query string using the client's request() method. ```php $response = $client->request('GET', 'http://httpbin.org/get?q=foo'); ``` -------------------------------- ### Mock Handler: Queue Responses and Exceptions Source: https://docs.guzzlephp.org/en/stable/testing.html Creates a MockHandler with queued responses and a RequestException, then uses a HandlerStack to intercept requests. Demonstrates shifting responses off the queue, resetting the queue, and appending new responses. When the queue is empty, an OutOfBoundsException is thrown. ```php use GuzzleHttp\Client; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Exception\RequestException; // Create a mock and queue two responses. $mock = new MockHandler([ new Response(200, ['X-Foo' => 'Bar'], 'Hello, World'), new Response(202, ['Content-Length' => 0]), new RequestException('Error Communicating with Server', new Request('GET', 'test')) ]); $handlerStack = HandlerStack::create($mock); $client = new Client(['handler' => $handlerStack]); // The first request is intercepted with the first response. $response = $client->request('GET', '/'); echo $response->getStatusCode(); //> 200 echo $response->getBody(); //> Hello, World // The second request is intercepted with the second response. echo $client->request('GET', '/')->getStatusCode(); //> 202 // Reset the queue and queue up a new response $mock->reset(); $mock->append(new Response(201)); // As the mock was reset, the new response is the 201 CREATED, // instead of the previously queued RequestException echo $client->request('GET', '/')->getStatusCode(); //> 201 ``` -------------------------------- ### Access request query string Source: https://docs.guzzlephp.org/en/stable/psr7.html Demonstrates retrieving the query string from a request URI using getQuery(). ```php $request = new Request('GET', 'http://httpbin.org/?foo=bar'); echo $request->getUri()->getQuery(); // foo=bar ``` -------------------------------- ### Require Composer's autoloader Source: https://docs.guzzlephp.org/en/stable/overview.html After installing Guzzle, include Composer's autoloader to use the library. ```php require 'vendor/autoload.php'; ``` -------------------------------- ### Retrieve response body with getBody() Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to fetch a response body using the getBody() method and echo it. The body is a stream that can be cast to a string. ```php $response = GuzzleHttp\get('http://httpbin.org/get'); echo $response->getBody(); // JSON string: { ... } ``` -------------------------------- ### Send async requests with sendAsync() and requestAsync() Source: https://docs.guzzlephp.org/en/stable/quickstart.html Shows how to send async requests using sendAsync() with a PSR-7 Request object, or requestAsync() with method and URI. Both return promises. ```php use GuzzleHttp\Psr7\Request; // Create a PSR-7 request object to send $headers = ['X-Foo' => 'Bar']; $body = 'Hello!'; $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body); $promise = $client->sendAsync($request); // Or, if you don't need to pass in a request instance: $promise = $client->requestAsync('GET', 'http://httpbin.org/get'); ``` -------------------------------- ### stream Source: https://docs.guzzlephp.org/en/stable/request-options.html Set to true to stream a response rather than downloading it all up-front. Example shows reading from the response body stream. ```APIDOC ## stream ### Description Set to `true` to stream a response rather than download it all up-front. ### Types - bool ### Default `false` ### Constant `GuzzleHttp\RequestOptions::STREAM` ### Request Example ```php $response = $client->request('GET', '/stream/20', ['stream' => true]); // Read bytes off of the stream until the end of the stream is reached $body = $response->getBody(); while (!$body->eof()) { echo $body->read(1024); } ``` ### Note Streaming response support must be implemented by the HTTP handler used by a client. This option might not be supported by every HTTP handler, but the interface of the response object remains the same regardless of whether or not it is supported by the handler. ``` -------------------------------- ### Attaching middleware to a client via HandlerStack Source: https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html Shows how to create a HandlerStack with a CurlHandler and push the add_header middleware onto it, then create a Guzzle client using that stack. This causes the middleware to be applied to every request. ```php use GuzzleHttp\HandlerStack; use GuzzleHttp\Handler\CurlHandler; use GuzzleHttp\Client; $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(add_header('X-Foo', 'bar')); $client = new Client(['handler' => $stack]); ``` -------------------------------- ### Force HTTP/1.0 with GuzzleHttp\RequestOptions::VERSION Source: https://docs.guzzlephp.org/en/stable/request-options.html Sets the HTTP protocol version to 1.0 for a GET request. The default version is 1.1. ```php // Force HTTP/1.0 $request = $client->request('GET', '/get', ['version' => 1.0]); ``` -------------------------------- ### Set up history middleware to track requests Source: https://docs.guzzlephp.org/en/stable/testing.html Use GuzzleHttp\Middleware::history to record requests and responses in a container. Add the middleware to a handler stack and create a client with that stack. After sending requests, the container holds transactions with 'request', 'response', 'error', and 'options' keys. ```php use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; $container = []; $history = Middleware::history($container); $handlerStack = HandlerStack::create(); // or $handlerStack = HandlerStack::create($mock); if using the Mock handler. // Add the history middleware to the handler stack. $handlerStack->push($history); $client = new Client(['handler' => $handlerStack]); $client->request('GET', 'http://httpbin.org/get'); $client->request('HEAD', 'http://httpbin.org/get'); // Count the number of transactions echo count($container); //> 2 // Iterate over the requests and responses foreach ($container as $transaction) { echo $transaction['request']->getMethod(); //> GET, HEAD if ($transaction['response']) { echo $transaction['response']->getStatusCode(); //> 200, 200 } elseif ($transaction['error']) { echo $transaction['error']; //> exception } var_dump($transaction['options']); //> dumps the request options of the sent request. } ``` -------------------------------- ### Handle promise fulfillment and rejection with then() Source: https://docs.guzzlephp.org/en/stable/quickstart.html Shows how to chain then() calls on a promise returned by an async request. The fulfillment callback receives a ResponseInterface, and the rejection callback receives a RequestException. ```php use Psr\Http\Message\ResponseInterface; use GuzzleHttp\Exception\RequestException; $promise = $client->requestAsync('GET', 'http://httpbin.org/get'); $promise->then( function (ResponseInterface $res) { echo $res->getStatusCode() . "\n"; }, function (RequestException $e) { echo $e->getMessage() . "\n"; echo $e->getRequest()->getMethod(); } ); ``` -------------------------------- ### Access request scheme Source: https://docs.guzzlephp.org/en/stable/psr7.html Demonstrates retrieving the scheme of a request URI using getScheme() and echoing the full URI. ```php $request = new Request('GET', 'http://httpbin.org'); echo $request->getUri()->getScheme(); // http echo $request->getUri(); // http://httpbin.org ``` -------------------------------- ### Set request timeout with GuzzleHttp\RequestOptions::TIMEOUT Source: https://docs.guzzlephp.org/en/stable/request-options.html Sets a timeout of 3.14 seconds for a GET request. If the server does not respond within that time, a TransferException is thrown. ```php // Timeout if a server does not return a response in 3.14 seconds. $client->request('GET', '/delay/5', ['timeout' => 3.14]); // PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\TransferException' ``` -------------------------------- ### Inspect received requests with Server::received() Source: https://docs.guzzlephp.org/en/stable/testing.html Call Server::received() to get an array of responses (or requests) that the server has received. Iterate over them to access their status codes. ```php foreach (Server::received() as $response) { echo $response->getStatusCode(); } ``` -------------------------------- ### Using the proxy request option with a string Source: https://docs.guzzlephp.org/en/stable/request-options.html Passes a string to specify an HTTP proxy for all protocols. The default is none and the constant is GuzzleHttp\RequestOptions::PROXY. ```php $client->request('GET', '/', ['proxy' => 'http://localhost:8125']); ``` -------------------------------- ### Create a PSR-7 response with GuzzleHttp\Psr7\Response Source: https://docs.guzzlephp.org/en/stable/psr7.html Use the Response class to create an HTTP response. The constructor requires no arguments, defaulting to status 200 and protocol 1.1. Optional arguments include status, headers, body, and protocol version. ```php use GuzzleHttp\Psr7\Response; // The constructor requires no arguments. $response = new Response(); echo $response->getStatusCode(); // 200 echo $response->getProtocolVersion(); // 1.1 // You can supply any number of optional arguments. $status = 200; $headers = ['X-Foo' => 'Bar']; $body = 'hello!'; $protocol = '1.1'; $response = new Response($status, $headers, $body, $protocol); ``` -------------------------------- ### Check if a header exists with hasHeader() Source: https://docs.guzzlephp.org/en/stable/psr7.html Use the hasHeader() method to check if a request or response has a specific header. The example creates a request with an 'X-Foo' header and checks for its presence. ```php use GuzzleHttp\Psr7; $request = new Psr7\Request('GET', '/', ['X-Foo' => 'bar']); if ($request->hasHeader('X-Foo')) { echo 'It is there'; } ``` -------------------------------- ### Use a shared client cookie jar with 'cookies' => true Source: https://docs.guzzlephp.org/en/stable/quickstart.html Set 'cookies' to true in the client constructor to use a shared cookie jar for all requests made by that client. ```php // Use a shared client cookie jar $client = new \GuzzleHttp\Client(['cookies' => true]); $r = $client->request('GET', 'http://httpbin.org/cookies'); ``` -------------------------------- ### Custom middleware to add a response header Source: https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html Example of a middleware that modifies the response by adding a header. It uses the promise returned by the downstream handler and attaches a then() callback to add the header to the response. ```php use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use GuzzleHttp\HandlerStack; use GuzzleHttp\Handler\CurlHandler; use GuzzleHttp\Client; function add_response_header($header, $value) { return function (callable $handler) use ($header, $value) { return function ( RequestInterface $request, array $options ) use ($handler, $header, $value) { $promise = $handler($request, $options); return $promise->then( function (ResponseInterface $response) use ($header, $value) { return $response->withHeader($header, $value); } ); }; }; } $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(add_response_header('X-Foo', 'bar')); $client = new Client(['handler' => $stack]); ``` -------------------------------- ### Access stream metadata with getMetadata() Source: https://docs.guzzlephp.org/en/stable/psr7.html Shows how to retrieve stream metadata using getMetadata(), including the URI, and check stream capabilities with isReadable(), isWritable(), and isSeekable(). ```php use GuzzleHttp\Psr7; $resource = Psr7\Utils::tryFopen('/path/to/file', 'r'); $stream = Psr7\Utils::streamFor($resource); echo $stream->getMetadata('uri'); // /path/to/file var_export($stream->isReadable()); // true var_export($stream->isWritable()); // false var_export($stream->isSeekable()); // true ``` -------------------------------- ### Set query parameters in request URI Source: https://docs.guzzlephp.org/en/stable/quickstart.html Send a GET request with query string parameters embedded directly in the URI. The query string is part of the URL passed to the request method. ```php $response = $client->request('GET', 'http://httpbin.org?foo=bar'); ``` -------------------------------- ### Send async requests with magic methods Source: https://docs.guzzlephp.org/en/stable/quickstart.html Shows how to send asynchronous requests using the magic async methods on a Guzzle client. Each method returns a promise that implements the Promises/A+ spec. ```php $promise = $client->getAsync('http://httpbin.org/get'); $promise = $client->deleteAsync('http://httpbin.org/delete'); $promise = $client->headAsync('http://httpbin.org/get'); $promise = $client->optionsAsync('http://httpbin.org/get'); $promise = $client->patchAsync('http://httpbin.org/patch'); $promise = $client->postAsync('http://httpbin.org/post'); $promise = $client->putAsync('http://httpbin.org/put'); ``` -------------------------------- ### Configure CurlMultiHandler with cURL multi options Source: https://docs.guzzlephp.org/en/stable/faq.html For asynchronous requests using the cURL multi handler, pass an associative array in the 'options' key of the CurlMultiHandler constructor. This example sets CURLMOPT_MAX_TOTAL_CONNECTIONS and CURLMOPT_MAX_HOST_CONNECTIONS. ```php use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\Handler\CurlMultiHandler; $client = new Client(['handler' => HandlerStack::create(new CurlMultiHandler([ 'options' => [ CURLMOPT_MAX_TOTAL_CONNECTIONS => 50, CURLMOPT_MAX_HOST_CONNECTIONS => 5, ] ]))]); ``` -------------------------------- ### Custom middleware to add a request header Source: https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html Example of a middleware that adds a header to each request before passing it to the downstream handler. The middleware is created with a header name and value, and returns a composed handler that modifies the request. ```php use Psr\Http\Message\RequestInterface; function add_header($header, $value) { return function (callable $handler) use ($header, $value) { return function ( RequestInterface $request, array $options ) use ($handler, $header, $value) { $request = $request->withHeader($header, $value); return $handler($request, $options); }; }; } ``` -------------------------------- ### Parse complex headers with Header::parse() Source: https://docs.guzzlephp.org/en/stable/psr7.html Use Guzzle's Header::parse() to parse complex headers like Link headers into a structured array. The example parses a Link header and outputs the result. ```php use GuzzleHttp\Psr7; $request = new Psr7\Request('GET', '/', [ 'Link' => '; rel="front"; type="image/jpeg"' ]); $parsed = Psr7\Header::parse($request->getHeader('Link')); var_export($parsed); ``` ```php array ( 0 => array ( 0 => '', 'rel' => 'front', 'type' => 'image/jpeg', ), ) ``` -------------------------------- ### Run Guzzle tests Source: https://docs.guzzlephp.org/en/stable/overview.html Runs the unit tests for Guzzle using the Makefile. ```bash make test ``` -------------------------------- ### Access response body as string or stream Source: https://docs.guzzlephp.org/en/stable/quickstart.html Retrieve the response body as a stream object. The body can be echoed directly, cast to a string, read a specific number of bytes with read(), or get the remaining contents with getContents(). ```php $body = $response->getBody(); // Implicitly cast the body to a string and echo it echo $body; // Explicitly cast the body to a string $stringBody = (string) $body; // Read 10 bytes from the body $tenBytes = $body->read(10); // Read the remaining contents of the body as a string $remainingBytes = $body->getContents(); ``` -------------------------------- ### Send concurrent requests with Promise\Utils::unwrap() and settle() Source: https://docs.guzzlephp.org/en/stable/quickstart.html Shows how to send multiple requests concurrently using promises. Uses Promise\Utils::unwrap() to wait for all requests and throw on failure, and Promise\Utils::settle() to wait even if some fail. Responses are keyed by the promise array keys. ```php use GuzzleHttp\Client; use GuzzleHttp\Promise; $client = new Client(['base_uri' => 'http://httpbin.org/']); // Initiate each request but do not block $promises = [ 'image' => $client->getAsync('/image'), 'png' => $client->getAsync('/image/png'), 'jpeg' => $client->getAsync('/image/jpeg'), 'webp' => $client->getAsync('/image/webp') ]; // Wait for the requests to complete; throws a ConnectException // if any of the requests fail $responses = Promise\Utils::unwrap($promises); // You can access each response using the key of the promise echo $responses['image']->getHeader('Content-Length')[0]; echo $responses['png']->getHeader('Content-Length')[0]; // Wait for the requests to complete, even if some of them fail $responses = Promise\Utils::settle($promises)->wait(); // Values returned above are wrapped in an array with 2 keys: "state" (either fulfilled or rejected) and "value" (contains the response) echo $responses['image']['state']; // returns "fulfilled" echo $responses['image']['value']->getHeader('Content-Length')[0]; echo $responses['png']['value']->getHeader('Content-Length')[0]; ``` -------------------------------- ### Get status code and reason phrase from response Source: https://docs.guzzlephp.org/en/stable/quickstart.html Retrieve the HTTP status code and reason phrase from a PSR-7 response object. The status code is an integer (e.g., 200) and the reason phrase is a string (e.g., 'OK'). ```php $code = $response->getStatusCode(); // 200 $reason = $response->getReasonPhrase(); // OK ``` -------------------------------- ### Basic HTTP authentication with 'auth' option Source: https://docs.guzzlephp.org/en/stable/request-options.html Use the 'auth' option with an array containing username and password to enable basic HTTP authentication. This is the default authentication type if none is specified. ```php $client->request('GET', '/get', ['auth' => ['username', 'password']]); ``` -------------------------------- ### on_headers: Reject responses greater than 1024 bytes Source: https://docs.guzzlephp.org/en/stable/request-options.html Use the on_headers option to inspect response headers before the body downloads. The callable receives a Psr\Http\Message\ResponseInterface; throwing an exception rejects the promise with a GuzzleHttp\Exception\RequestException wrapping it. This example rejects responses whose Content-Length exceeds 1024 bytes. ```php // Reject responses that are greater than 1024 bytes. $client->request('GET', 'http://httpbin.org/stream/1024', [ 'on_headers' => function (ResponseInterface $response) { if ($response->getHeaderLine('Content-Length') > 1024) { throw new Exception('The file is too big!'); } } ]); ```