Welcome to Test’s documentation!¶
Contents:
Overview¶
Requirements¶
- PHP 5.5.0
- To use the PHP stream handler,
allow_url_fopen
must be enabled in your system’s php.ini. - To use the cURL handler, you must have a recent version of cURL >= 7.19.4 compiled with OpenSSL and zlib.
Note
Guzzle no longer requires cURL in order to send HTTP requests. Guzzle will use the PHP stream wrapper to send HTTP requests if cURL is not installed. Alternatively, you can provide your own HTTP handler used to send requests.
Installation¶
The recommended way to install Guzzle is with Composer. Composer is a dependency management tool for PHP that allows you to declare the dependencies your project needs and installs them into your project.
# Install Composer
curl -sS https://getcomposer.org/installer | php
You can add Guzzle as a dependency using the composer.phar CLI:
php composer.phar require guzzlehttp/guzzle:~6.0
Alternatively, you can specify Guzzle as a dependency in your project’s existing composer.json file:
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
After installing, you need to require Composer’s autoloader:
require 'vendor/autoload.php';
You can find out more on how to install Composer, configure autoloading, and other best-practices for defining dependencies at getcomposer.org.
Bleeding edge¶
During your development, you can keep up with the latest changes on the master
branch by setting the version requirement for Guzzle to ~6.0@dev
.
{
"require": {
"guzzlehttp/guzzle": "~6.0@dev"
}
}
License¶
Licensed using the MIT license.
Copyright (c) 2015 Michael Dowling <https://github.com/mtdowling>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Contributing¶
Guidelines¶
- Guzzle utilizes PSR-1, PSR-2, PSR-4, and PSR-7.
- Guzzle is meant to be lean and fast with very few dependencies. This means that not every feature request will be accepted.
- Guzzle has a minimum PHP version requirement of PHP 5.5. Pull requests must not require a PHP version greater than PHP 5.5 unless the feature is only utilized conditionally.
- All pull requests must include unit tests to ensure the change works as expected and to prevent regressions.
Running the tests¶
In order to contribute, you’ll need to checkout the source from GitHub and install Guzzle’s dependencies using Composer:
git clone https://github.com/guzzle/guzzle.git
cd guzzle && curl -s http://getcomposer.org/installer | php && ./composer.phar install --dev
Guzzle is unit tested with PHPUnit. Run the tests using the Makefile:
make test
Note
You’ll need to install node.js v0.5.0 or newer in order to perform integration tests on Guzzle’s HTTP handlers.
Reporting a security vulnerability¶
We want to ensure that Guzzle is a secure HTTP client library for everyone. If you’ve discovered a security vulnerability in Guzzle, we appreciate your help in disclosing it to us in a responsible manner.
Publicly disclosing a vulnerability can put the entire community at risk. If you’ve discovered a security concern, please email us at security@guzzlephp.org. We’ll work with you to make sure that we understand the scope of the issue, and that we fully address your concern. We consider correspondence sent to security@guzzlephp.org our highest priority, and work to address any issues that arise as quickly as possible.
After a security vulnerability has been corrected, a security hotfix release will be deployed as soon as possible.
Quickstart¶
This page provides a quick introduction to Guzzle and introductory examples. If you have not already installed, Guzzle, head over to the Installation page.
Making a Request¶
You can send requests with Guzzle using a GuzzleHttp\ClientInterface
object.
Creating a Client¶
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,
]);
The client constructor accepts an associative array of options:
base_uri
(string|UriInterface) Base URI of the client that is merged into relative URIs. Can be a string or instance of UriInterface. When a relative URI is provided to a client, the client will combine the base URI with the relative URI using the rules described in RFC 3986, section 2.
// Create a client with a base URI $client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']); // Send a request to https://foo.com/api/test $response = $client->get('test'); // Send a request to https://foo.com/root $response = $client->get('/root');
Don’t feel like reading RFC 3986? Here are some quick examples on how a
base_uri
is resolved with another URI.base_uri URI Result http://foo.com
/bar
http://foo.com/bar
http://foo.com/foo
/bar
http://foo.com/bar
http://foo.com/foo
bar
http://foo.com/bar
http://foo.com/foo/
bar
http://foo.com/foo/bar
http://foo.com
http://baz.com
http://baz.com
http://foo.com/?bar
bar
http://foo.com/bar
handler
- (callable) Function that transfers HTTP requests over the wire. The
function is called with a
Psr7\Http\Message\RequestInterface
and array of transfer options, and must return aGuzzleHttp\Promise\PromiseInterface
that is fulfilled with aPsr7\Http\Message\ResponseInterface
on success.handler
is a constructor only option that cannot be overridden in per/request options. ...
- (mixed) All other options passed to the constructor are used as default request options with every request created by the client.
Sending Requests¶
Magic methods on the client make it easy to send synchronous requests:
$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');
You can create a request and then send the request with the client when you’re ready:
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http:/httpbin.org/put');
$response = $client->send($request, ['timeout' => 2]);
Client objects provide a great deal of flexibility in how request are transferred including default request options, default handler stack middleware that are used by each request, and a base URI that allows you to send requests with relative URIs.
You can find out more about client middleware in the
handlers-and-middleware
page of the documentation.
Async Requests¶
You can send asynchronous requests using the magic methods provided by a client:
$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');
You can also use the sendAsync() and requestAsync() methods of a client:
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);
// Or, if you don't need to pass in a request instance:
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
The promise returned by these methods implements the
Promises/A+ spec, provided by the
Guzzle promises library. This means
that you can chain then()
calls off of the promise. These then calls are
either fulfilled with a successful Psr\Http\Message\ResponseInterface
or
rejected with an exception.
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();
}
);
Concurrent requests¶
You can send multiple requests concurrently using promises and asynchronous requests.
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 on all of the requests to complete.
$results = Promise\unwrap($promises);
// You can access each result using the key provided to the unwrap
// function.
echo $results['image']->getHeader('Content-Length');
echo $results['png']->getHeader('Content-Length');
You can use the GuzzleHttp\Pool
object when you have an indeterminate
amount of requests you wish to send.
use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$client = new Client();
$requests = function ($total) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', $uri);
}
};
$pool = new Pool($client, $requests(100), [
'concurrency' => 5,
'fulfilled' => function ($response, $index) {
// this is delivered each successful response
},
'rejected' => function ($reason, $index) {
// this is delivered each failed request
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
Using Responses¶
In the previous examples, we retrieved a $response
variable or we were
delivered a response from a promise. The response object implements a PSR-7
response, Psr\Http\Message\ResponseInterface
, and contains lots of
helpful information.
You can get the status code and reason phrase of the response:
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
You can retrieve headers from the response:
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
// Get a header from the response.
echo $response->getHeader('Content-Length');
// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
Query String Parameters¶
You can provide query string parameters with a request in several ways.
You can set query string parameters in the request’s URI:
$response = $client->get('http://httpbin.org?foo=bar');
You can specify the query string parameters using the query
request
option as an array.
$client->get('http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Providing the option as an array will use PHP’s http_build_query
function
to format the query string.
And finally, you can provide the query
request option as a string.
$client->get('http://httpbin.org', ['query' => 'foo=bar']);
Uploading Data¶
Guzzle provides several methods for uploading data.
You can send requests that contain a stream of data by passing a string,
resource returned from fopen
, or an instance of a
Psr\Http\Message\StreamInterface
to the body
request option.
// Provide the body as a string.
$r = $client->post('http://httpbin.org/post', ['body' => 'raw data']);
// Provide an fopen resource.
$body = fopen('/path/to/file', 'r');
$r = $client->post('http://httpbin.org/post', ['body' => $body]);
// Use the stream_for() function to create a PSR-7 stream.
$body = \GuzzleHttp\Psr7\stream_for('hello!');
$r = $client->post('http://httpbin.org/post', ['body' => $body]);
An easy way to upload JSON data and set the appropriate header is using the
json
request option:
$r = $client->put('http://httpbin.org/put', [
'json' => ['foo' => 'bar']
]);
POST/Form Requests¶
In addition to specifying the raw data of a request using the body
request
option, Guzzle provides helpful abstractions over sending POST data.
Sending form fields¶
Sending application/x-www-form-urlencoded
POST requests requires that you
specify the POST fields as an array in the form_params
request options.
$response = $client->post('http://httpbin.org/post', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
Sending form files¶
You can send files along with a form (multipart/form-data
POST requests),
using the multipart
request option. multipart
accepts an array of
associative arrays, where each associative array contains the following keys:
- name: (required, string) key mapping to the form field name.
- contents: (required, mixed) Provide a string to send the contents of the
file as a string, provide an fopen resource to stream the contents from a
PHP stream, or provide a
Psr\Http\Message\StreamInterface
to stream the contents from a PSR-7 stream.
$response = $client->post('http://httpbin.org/post', [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'other_file',
'contents' => 'hello',
'filename' => 'filename.txt',
'headers' => [
'X-Foo' => 'this is an extra header to include'
]
]
]
]);
Cookies¶
Guzzle can maintain a cookie session for you if instructed using the
cookies
request option. When sending a request, the cookies
option
must be set an an instance of GuzzleHttp\Subscriber\CookieJar\CookieJarInterface
.
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->get('http://httpbin.org/cookies', ['cookies' => $jar]);
You can set cookies
to true
in a client constructor if you would like
to use a shared cookie jar for all requests.
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->get('http://httpbin.org/cookies');
Redirects¶
Guzzle will automatically follow redirects unless you tell it not to. You can
customize the redirect behavior using the allow_redirects
request option.
- Set to
true
to enable normal redirects with a maximum number of 5 redirects. This is the default setting. - Set to
false
to disable redirects. - Pass an associative array containing the ‘max’ key to specify the maximum number of redirects and optionally provide a ‘strict’ key value to specify whether or not to use strict RFC compliant redirects (meaning redirect POST requests with POST requests vs. doing what most browsers do which is redirect POST requests with GET requests).
$response = $client->get('http://github.com');
echo $response->getStatusCode();
// 200
The following example shows that redirects can be disabled.
$response = $client->get('http://github.com', ['allow_redirects' => false]);
echo $response->getStatusCode();
// 301
Exceptions¶
Guzzle throws exceptions for errors that occur during a transfer.
In the event of a networking error (connection timeout, DNS errors, etc.), a
GuzzleHttp\Exception\RequestException
is thrown. This exception extends fromGuzzleHttp\Exception\TransferException
. Catching this exception will catch any exception that can be thrown while transferring requests.use GuzzleHttp\Exception\RequestException; try { $client->get('https://github.com/_abc_123_404'); } catch (RequestException $e) { echo $e->getRequest(); if ($e->hasResponse()) { echo $e->getResponse(); } }
A
GuzzleHttp\Exception\ConnectException
exception is thrown in the event of a networking error. This exception extends fromGuzzleHttp\Exception\RequestException
.A
GuzzleHttp\Exception\ClientException
is thrown for 400 level errors if thehttp_errors
request option is set to true. This exception extends fromGuzzleHttp\Exception\BadResponseException
andGuzzleHttp\Exception\BadResponseException
extends fromGuzzleHttp\Exception\RequestException
.use GuzzleHttp\Exception\ClientException; try { $client->get('https://github.com/_abc_123_404'); } catch (ClientException $e) { echo $e->getRequest(); echo $e->getResponse(); }
A
GuzzleHttp\Exception\ServerException
is thrown for 500 level errors if thehttp_errors
request option is set to true. This exception extends fromGuzzleHttp\Exception\BadResponseException
.A
GuzzleHttp\Exception\TooManyRedirectsException
is thrown when too many redirects are followed. This exception extends fromGuzzleHttp\Exception\RequestException
.
All of the above exceptions extend from
GuzzleHttp\Exception\TransferException
.
Environment Variables¶
Guzzle exposes a few environment variables that can be used to customize the behavior of the library.
GUZZLE_CURL_SELECT_TIMEOUT
- Controls the duration in seconds that a curl_multi_* handler will use when
selecting on curl handles using
curl_multi_select()
. Some systems have issues with PHP’s implementation ofcurl_multi_select()
where calling this function always results in waiting for the maximum duration of the timeout. HTTP_PROXY
- Defines the proxy to use when sending requests using the “http” protocol.
HTTPS_PROXY
- Defines the proxy to use when sending requests using the “https” protocol.
Relevant ini Settings¶
Guzzle can utilize PHP ini settings when configuring clients.
openssl.cafile
- Specifies the path on disk to a CA file in PEM format to use when sending requests over “https”. See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults
TestMD!¶
We are testing md!
Second heading!¶
Testing MD files.
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, ]);
DateTime Class¶
-
class
DateTime
¶ Datetime class
-
setDate
($year, $month, $day)¶ Set the date.
Parameters: - $year (int) – The year.
- $month (int) – The month.
- $day (int) – The day.
Returns: Either false on failure, or the datetime object for method chaining.
-
setTime
($hour, $minute[, $second])¶ Set the time.
Parameters: - $hour (int) – The hour
- $minute (int) – The minute
- $second (int) – The second
Returns: Either false on failure, or the datetime object for method chaining.
-
constant
ATOM
¶ Y-m-dTH:i:sP
-