Requests

Requests are sent from a client to a server. Requests include the method to be applied to a resource, the identifier of the resource, and the protocol version to use.

Clients are used to create request messages. More precisely, clients use a GuzzleHttp\Message\MessageFactoryInterface to create request messages. You create requests with a client using the createRequest() method.

  1. // Create a request but don't send it immediately
  2. $request = $client->createRequest('GET', 'http://httpbin.org/get');

Request Methods

When creating a request, you are expected to provide the HTTP method you wish to perform. You can specify any method you’d like, including a custom method that might not be part of RFC 7231 (like “MOVE”).

  1. // Create a request using a completely custom HTTP method
  2. $request = $client->createRequest('MOVE', 'http://httpbin.org/move', ['exceptions' => false]);
  3. echo $request->getMethod();
  4. // MOVE
  5. $response = $client->send($request);
  6. echo $response->getStatusCode();
  7. // 405

You can create and send a request using methods on a client that map to the HTTP method you wish to use.

GET:$client->get(‘http://httpbin.org/get‘, [/ options /])
POST:$client->post(‘http://httpbin.org/post‘, [/ options /])
HEAD:$client->head(‘http://httpbin.org/get‘, [/ options /])
PUT:$client->put(‘http://httpbin.org/put‘, [/ options /])
DELETE:$client->delete(‘http://httpbin.org/delete‘, [/ options /])
OPTIONS:$client->options(‘http://httpbin.org/get‘, [/ options /])
PATCH:$client->patch(‘http://httpbin.org/put‘, [/ options /])
  1. $response = $client->patch('http://httpbin.org/patch', ['body' => 'content']);

Request URI

The resource you are requesting with an HTTP request is identified by the path of the request, the query string, and the “Host” header of the request.

When creating a request, you can provide the entire resource URI as a URL.

  1. $response = $client->get('http://httbin.org/get?q=foo');

Using the above code, you will send a request that uses httpbin.org as the Host header, sends the request over port 80, uses /get as the path, and sends ?q=foo as the query string. All of this is parsed automatically from the provided URI.

Sometimes you don’t know what the entire request will be when it is created. In these cases, you can modify the request as needed before sending it using the createRequest() method of the client and methods on the request that allow you to change it.

  1. $request = $client->createRequest('GET', 'http://httbin.org');

You can change the path of the request using setPath():

  1. $request->setPath('/get');
  2. echo $request->getPath();
  3. // /get
  4. echo $request->getUrl();
  5. // http://httpbin.com/get

Scheme

The scheme of a request specifies the protocol to use when sending the request. When using Guzzle, the scheme can be set to “http” or “https”.

You can change the scheme of the request using the setScheme() method:

  1. $request = $client->createRequest('GET', 'http://httbin.org');
  2. $request->setScheme('https');
  3. echo $request->getScheme();
  4. // https
  5. echo $request->getUrl();
  6. // https://httpbin.com/get

Port

No port is necessary when using the “http” or “https” schemes, but you can override the port using setPort(). If you need to modify the port used with the specified scheme from the default setting, then you must use the setPort() method.

  1. $request = $client->createRequest('GET', 'http://httbin.org');
  2. $request->setPort(8080);
  3. echo $request->getPort();
  4. // 8080
  5. echo $request->getUrl();
  6. // https://httpbin.com:8080/get
  7. // Set the port back to the default value for the scheme
  8. $request->setPort(443);
  9. echo $request->getUrl();
  10. // https://httpbin.com/get

Query string

You can get the query string of the request using the getQuery() method. This method returns a GuzzleHttp\Query object. A Query object can be accessed like a PHP array, iterated in a foreach statement like a PHP array, and cast to a string.

  1. $request = $client->createRequest('GET', 'http://httbin.org');
  2. $query = $request->getQuery();
  3. $query['foo'] = 'bar';
  4. $query['baz'] = 'bam';
  5. $query['bam'] = ['test' => 'abc'];
  6. echo $request->getQuery();
  7. // foo=bar&baz=bam&bam%5Btest%5D=abc
  8. echo $request->getQuery()['foo'];
  9. // bar
  10. echo $request->getQuery()->get('foo');
  11. // bar
  12. echo $request->getQuery()->get('foo');
  13. // bar
  14. var_export($request->getQuery()['bam']);
  15. // array('test' => 'abc')
  16. foreach ($query as $key => $value) {
  17. var_export($value);
  18. }
  19. echo $request->getUrl();
  20. // https://httpbin.com/get?foo=bar&baz=bam&bam%5Btest%5D=abc
Query Aggregators

Query objects can store scalar values or arrays of values. When an array of values is added to a query object, the query object uses a query aggregator to convert the complex structure into a string. Query objects will use PHP style query strings when complex query string parameters are converted to a string. You can customize how complex query string parameters are aggregated using the setAggregator() method of a query string object.

  1. $query->setAggregator($query::duplicateAggregator());

In the above example, we’ve changed the query object to use the “duplicateAggregator”. This aggregator will allow duplicate entries to appear in a query string rather than appending “[n]” to each value. So if you had a query string with ['a' => ['b', 'c']], the duplicate aggregator would convert this to “a=b&a=c” while the default aggregator would convert this to “a[0]=b&a[1]=c” (with urlencoded brackets).

The setAggregator() method accepts a callable which is used to convert a deeply nested array of query string variables into a flattened array of key value pairs. The callable accepts an array of query data and returns a flattened array of key value pairs where each value is an array of strings. You can use the GuzzleHttp\Query::walkQuery() static function to easily create custom query aggregators.

Host

You can change the host header of the request in a predictable way using the setHost() method of a request:

  1. $request->setHost('www.google.com');
  2. echo $request->getHost();
  3. // www.google.com
  4. echo $request->getUrl();
  5. // https://www.google.com/get?foo=bar&baz=bam

Note

The Host header can also be changed by modifying the Host header of a request directly, but modifying the Host header directly could result in sending a request to a different Host than what is specified in the Host header (sometimes this is actually the desired behavior).

Resource

You can use the getResource() method of a request to return the path and query string of a request in a single string.

  1. $request = $client->createRequest('GET', 'http://httpbin.org/get?baz=bar');
  2. echo $request->getResource();
  3. // /get?baz=bar

Request Config

Request messages contain a configuration collection that can be used by event listeners and HTTP handlers to modify how a request behaves or is transferred over the wire. For example, many of the request options that are specified when creating a request are actually set as config options that are only acted upon by handlers and listeners when the request is sent.

You can get access to the request’s config object using the getConfig() method of a request.

  1. $request = $client->createRequest('GET', '/');
  2. $config = $request->getConfig();

The config object is a GuzzleHttp\Collection object that acts like an associative array. You can grab values from the collection using array like access. You can also modify and remove values using array like access.

  1. $config['foo'] = 'bar';
  2. echo $config['foo'];
  3. // bar
  4. var_export(isset($config['foo']));
  5. // true
  6. unset($config['foo']);
  7. var_export(isset($config['foo']));
  8. // false
  9. var_export($config['foo']);
  10. // NULL

HTTP handlers and event listeners can expose additional customization options through request config settings. For example, in order to specify custom cURL options to the cURL handler, you need to specify an associative array in the curl config request option.

  1. $client->get('/', [
  2. 'config' => [
  3. 'curl' => [
  4. CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
  5. CURLOPT_USERPWD => 'username:password'
  6. ]
  7. ]
  8. ]);

Consult the HTTP handlers and event listeners you are using to see if they allow customization through request configuration options.

Event Emitter

Request objects implement GuzzleHttp\Event\HasEmitterInterface, so they have a method called getEmitter() that can be used to get an event emitter used by the request. Any listener or subscriber attached to a request will only be triggered for the lifecycle events of a specific request. Conversely, adding an event listener or subscriber to a client will listen to all lifecycle events of all requests created by the client.

See Event System for more information.