Guzzle utilizes PSR-7 as the HTTP message interface. This allows Guzzle to workwith any other library that utilizes PSR-7 message interfaces.
Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTPresponses. Both requests and responses are referred to as messages.
Guzzle relies on theguzzlehttp/psr7 Composer package for its messageimplementation of PSR-7.
You can create a request using theGuzzleHttp\Psr7\Request class:
useGuzzleHttp\Psr7\Request;$request=newRequest('GET','http://httpbin.org/get');// You can provide other optional constructor arguments.$headers=['X-Foo'=>'Bar'];$body='hello!';$request=newRequest('PUT','http://httpbin.org/put',$headers,$body);
You can create a response using theGuzzleHttp\Psr7\Response class:
useGuzzleHttp\Psr7\Response;// The constructor requires no arguments.$response=newResponse();echo$response->getStatusCode();// 200echo$response->getProtocolVersion();// 1.1// You can supply any number of optional arguments.$status=200;$headers=['X-Foo'=>'Bar'];$body='hello!';$protocol='1.1';$response=newResponse($status,$headers,$body,$protocol);
Both request and response messages contain HTTP headers.
You can check if a request or response has a specific header using thehasHeader() method.
useGuzzleHttp\Psr7;$request=newPsr7\Request('GET','/',['X-Foo'=>'bar']);if($request->hasHeader('X-Foo')){echo'It is there';}
You can retrieve all the header values as an array of strings usinggetHeader().
$request->getHeader('X-Foo');// ['bar']// Retrieving a missing header returns an empty array.$request->getHeader('X-Bar');// []
You can iterate over the headers of a message using thegetHeaders()method.
foreach($request->getHeaders()as$name=>$values){echo$name.': '.implode(', ',$values)."\r\n";}
Some headers contain additional key value pair information. For example, Linkheaders contain a link and several key value pairs:
<http://foo.com>; rel="thing"; type="image/jpeg"
Guzzle provides a convenience feature that can be used to parse these types ofheaders:
useGuzzleHttp\Psr7;$request=newPsr7\Request('GET','/',['Link'=>'<http:/.../front.jpeg>; rel="front"; type="image/jpeg"']);$parsed=Psr7\Header::parse($request->getHeader('Link'));var_export($parsed);
Will output:
array(0=>array(0=>'<http:/.../front.jpeg>','rel'=>'front','type'=>'image/jpeg',),)
The result contains a hash of key value pairs. Header values that have no key(i.e., the link) are indexed numerically while headers parts that form a keyvalue pair are added as a key value pair.
Both request and response messages can contain a body.
You can retrieve the body of a message using thegetBody() method:
$response=GuzzleHttp\get('http://httpbin.org/get');echo$response->getBody();// JSON string: { ... }
The body used in request and response objects is aPsr\Http\Message\StreamInterface. This stream is used for bothuploading data and downloading data. Guzzle will, by default, store the body ofa message in a stream that uses PHP temp streams. When the size of the bodyexceeds 2 MB, the stream will automatically switch to storing data on diskrather than in memory (protecting your application from memory exhaustion).
The easiest way to create a body for a message is using thestreamFormethod from theGuzzleHttp\Psr7\Utils class --Utils::streamFor. This method accepts strings, resources,callables, iterators, other streamables, and returns an instance ofPsr\Http\Message\StreamInterface.
The body of a request or response can be cast to a string or you can read andwrite bytes off of the stream as needed.
useGuzzleHttp\Stream\Stream;$response=$client->request('GET','http://httpbin.org/get');echo$response->getBody()->read(4);echo$response->getBody()->read(4);echo$response->getBody()->read(1024);var_export($response->eof());
Requests are sent from a client to a server. Requests include the method tobe applied to a resource, the identifier of the resource, and the protocolversion to use.
When creating a request, you are expected to provide the HTTP method you wishto perform. You can specify any method you'd like, including a custom methodthat might not be part of RFC 7231 (like "MOVE").
// Create a request using a completely custom HTTP method$request=new\GuzzleHttp\Psr7\Request('MOVE','http://httpbin.org/move');echo$request->getMethod();// MOVE
You can create and send a request using methods on a client that map to theHTTP method you wish to use.
$client->get('http://httpbin.org/get',[/**options**/])$client->post('http://httpbin.org/post',[/**options**/])$client->head('http://httpbin.org/get',[/**options**/])$client->put('http://httpbin.org/put',[/**options**/])$client->delete('http://httpbin.org/delete',[/**options**/])$client->options('http://httpbin.org/get',[/**options**/])$client->patch('http://httpbin.org/put',[/**options**/])For example:
$response=$client->patch('http://httpbin.org/patch',['body'=>'content']);
The request URI is represented by aPsr\Http\Message\UriInterface object.Guzzle provides an implementation of this interface using theGuzzleHttp\Psr7\Uri class.
When creating a request, you can provide the URI as a string or an instance ofPsr\Http\Message\UriInterface.
$response=$client->request('GET','http://httpbin.org/get?q=foo');
Thescheme of a requestspecifies the protocol to use when sending the request. When using Guzzle, thescheme can be set to "http" or "https".
$request=newRequest('GET','http://httpbin.org');echo$request->getUri()->getScheme();// httpecho$request->getUri();// http://httpbin.org
The host is accessible using the URI owned by the request or by accessing theHost header.
$request=newRequest('GET','http://httpbin.org');echo$request->getUri()->getHost();// httpbin.orgecho$request->getHeader('Host');// httpbin.org
No port is necessary when using the "http" or "https" schemes.
$request=newRequest('GET','http://httpbin.org:8080');echo$request->getUri()->getPort();// 8080echo$request->getUri();// http://httpbin.org:8080
The path of a request is accessible via the URI object.
$request=newRequest('GET','http://httpbin.org/get');echo$request->getUri()->getPath();// /get
The contents of the path will be automatically filtered to ensure that onlyallowed characters are present in the path. Any characters that are not allowedin the path will be percent-encoded according toRFC 3986 section 3.3
The query string of a request can be accessed using thegetQuery() of theURI object owned by the request.
$request=newRequest('GET','http://httpbin.org/?foo=bar');echo$request->getUri()->getQuery();// foo=bar
The contents of the query string will be automatically filtered to ensure thatonly allowed characters are present in the query string. Any characters thatare not allowed in the query string will be percent-encoded according toRFC 3986 section 3.4
Responses are the HTTP messages a client receives from a server after sendingan HTTP request message.
The start-line of a response contains the protocol and protocol version,status code, and reason phrase.
$client=new\GuzzleHttp\Client();$response=$client->request('GET','http://httpbin.org/get');echo$response->getStatusCode();// 200echo$response->getReasonPhrase();// OKecho$response->getProtocolVersion();// 1.1
As described earlier, you can get the body of a response using thegetBody() method.
$body=$response->getBody();echo$body;// Cast to a string: { ... }$body->seek(0);// Rewind the body$body->read(1024);// Read bytes of the body
Guzzle uses PSR-7 stream objects to represent request and response messagebodies. These stream objects allow you to work with various types of data allusing a common interface.
HTTP messages consist of a start-line, headers, and a body. The body of an HTTPmessage can be very small or extremely large. Attempting to represent the bodyof a message as a string can easily consume more memory than intended becausethe body must be stored completely in memory. Attempting to store the body of arequest or response in memory would preclude the use of that implementation frombeing able to work with large message bodies. The StreamInterface is used inorder to hide the implementation details of where a stream of data is read fromor written to.
The PSR-7Psr\Http\Message\StreamInterface exposes several methodsthat enable streams to be read from, written to, and traversed effectively.
Streams expose their capabilities using three methods:isReadable(),isWritable(), andisSeekable(). These methods can be used by streamcollaborators to determine if a stream is capable of their requirements.
Each stream instance has various capabilities: they can be read-only,write-only, read-write, allow arbitrary random access (seeking forwards orbackwards to any location), or only allow sequential access (for example in thecase of a socket or pipe).
Guzzle uses theguzzlehttp/psr7 package to provide stream support. Moreinformation on using streams, creating streams, converting streams to PHPstream resource, and stream decorators can be found in theGuzzle PSR-7 documentation.
The best way to create a stream is using theGuzzleHttp\Psr7\Utils::streamFormethod. This method accepts strings, resources returned fromfopen(),an object that implements__toString(), iterators, callables, and instancesofPsr\Http\Message\StreamInterface.
useGuzzleHttp\Psr7;$stream=Psr7\Utils::streamFor('string data');echo$stream;// string dataecho$stream->read(3);// strecho$stream->getContents();// ing datavar_export($stream->eof());// truevar_export($stream->tell());// 11
You can create streams from iterators. The iterator can yield any number ofbytes per iteration. Any excess bytes returned by the iterator that were notrequested by a stream consumer will be buffered until a subsequent read.
useGuzzleHttp\Psr7;$generator=function($bytes){for($i=0;$i<$bytes;$i++){yield'.';}};$iter=$generator(1024);$stream=Psr7\Utils::streamFor($iter);echo$stream->read(3);// ...
Streams expose stream metadata through thegetMetadata() method. Thismethod provides the data you would retrieve when calling PHP'sstream_get_meta_data() function,and can optionally expose other custom data.
useGuzzleHttp\Psr7;$resource=Psr7\Utils::tryFopen('/path/to/file','r');$stream=Psr7\Utils::streamFor($resource);echo$stream->getMetadata('uri');// /path/to/filevar_export($stream->isReadable());// truevar_export($stream->isWritable());// falsevar_export($stream->isSeekable());// true
Adding custom functionality to streams is very simple with stream decorators.Guzzle provides several built-in decorators that provide additional streamfunctionality.