phasync
HTTP client / HttpClientOptions

Class

HttpClientOptions

The options of an HTTP request, as public properties that map to cURL options.

Introduction#

Every option defaults to null, meaning "not set": cURL's own default applies. The exception is followLocation, which defaults to true. Give an instance, or an array keyed by property name, to the HttpClient constructor for defaults, or to a request method for one request.

Class synopsis#

class HttpClientOptions {
    /* Methods */
    public HttpClientOptions::__construct(array $options = [])
    public HttpClientOptions::overrideFrom(
        HttpClientOptions|array|null $options
    ): HttpClientOptions
}

Properties#

NameTypeDescription
$userAgent?stringThe contents of the "User-Agent: " header to be used in a HTTP request.
$resumeFrom?intThe offset, in bytes, to resume a transfer from.
$ipResolve?intAllows an application to select what kind of IP addresses to use when resolving host names. This is only interesting when using host names that resolve addresses using more than one version of IP, possible values are CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6, by default CURL_IPRESOLVE_WHATEVER.
$autoReferer?booltrue to automatically set the Referer: field in requests where it follows a Location: redirect.
$crlf?booltrue to convert Unix newlines to CRLF newlines on transfers.
$disallowUsernameInUrl?booltrue to not allow URLs that include a username. Usernames are allowed by default (0).
$dnsShuffleAddresses?booltrue to shuffle the order of all returned addresses so that they will be used in a random order, when a name is resolved and more than one IP address is returned. This may cause IPv4 to be used before IPv6 or vice versa.
$haProxyProtocol?booltrue to send an HAProxy PROXY protocol v1 header at the start of the connection. The default action is not to send this header.
$followLocation?booltrue to follow any "Location: " header that the server sends as part of the HTTP header. See also {@see self::$maxRedirs}.
$forbidReuse?booltrue to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
$freshConnect?booltrue to force the use of a new connection instead of a cached one.
$tcpNoDelay?booltrue to disable TCP's Nagle algorithm, which tries to minimize the number of small packets on the network.
$httpProxyTunnel?booltrue to tunnel through a given HTTP proxy.
$httpContentDecoding?boolfalse to get the raw HTTP response body.
$sslEnableAlpn?boolfalse to disable ALPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2.
$sslEnableNpn?boolfalse to disable NPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2.
$sslVerifyPeer?boolfalse to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.
$proxySslVerifyPeer?boolfalse to stop cURL from verifying the HTTPS proxy's certificate. When false, the verification succeeds regardless.
$proxySslVerifyHost?boolfalse to accept the HTTPS proxy's certificate whatever names it holds; by default cURL verifies them against the proxy name. Use with caution.
$proxy?stringThe HTTP proxy to tunnel requests through.
$proxyAuth?intThe HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported.
$proxyPort?intThe port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY.
$proxyType?intEither CURLPROXY_HTTP (default), CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A or CURLPROXY_SOCKS5_HOSTNAME.
$pathAsIs?booltrue to not handle dot dot sequences.
$netRc?booltrue to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with.
$timeoutMs?intThe maximum number of milliseconds to allow cURL functions to execute. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. A transfer that exceeds it fails with a \RuntimeException when the response is read.
$connectTimeoutMs?intThe number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second.
$maxRedirs?intThe maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION. Default value of 20 is set to prevent infinite redirects. Setting to -1 allows infinite redirects, and 0 refuses all redirects.
$cookie?stringThe contents of the "Cookie: " header to be used in the HTTP request. Note that multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")
$cookieFile?stringThe name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.
$cookieJar?stringThe name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curl_close.
$encoding?stringThe contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent.
$postFieldsarray|string|nullThe full data to post in a HTTP "POST" operation. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. Files can be sent using CURLFile or CURLStringFile, in which case value must be an array.
$referer?stringThe contents of the "Referer: " header to be used in a HTTP request.
$range?stringRange(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
$username?stringThe user name to use in authentication.
$password?stringThe password to use in authentication.
$headers?arrayAn array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
$resolve?arrayProvide a custom address for a specific host and port pair. An array of hostname, port, and IP address strings, each element separated by a colon. In the format: array("example.com:80:127.0.0.1")

Methods#

MethodDescription
__constructCreate the options from an array of values keyed by property name.
overrideFromReturn a copy of this instance with the non-null values of $options applied on top.

Examples#

Example 1Defaults, and options for one request
use phasync\HttpClient\HttpClient;
use phasync\HttpClient\HttpClientOptions;

$base = require __DIR__ . '/../server.php';

$defaults            = new HttpClientOptions();
$defaults->userAgent = 'inventory-sync/1.0';
$defaults->timeoutMs = 5000;
$client              = new HttpClient($defaults);

$echo = json_decode((string) $client->get("$base/echo")->getBody(), true);
echo $echo['headers']['user-agent'], "\n";

// Options given to one request apply on top of the defaults, for that request only
$echo = json_decode((string) $client->get("$base/echo", ['userAgent' => 'one-off/2.0'])->getBody(), true);
echo $echo['headers']['user-agent'], "\n";

$echo = json_decode((string) $client->get("$base/echo")->getBody(), true);
echo $echo['headers']['user-agent'], "\n";
Output
inventory-sync/1.0
one-off/2.0
inventory-sync/1.0
Example 2
$options = new HttpClientOptions(['timeoutMs' => 3000, 'userAgent' => 'my-app/1.0']);
$client  = new HttpClient($options);

$client->get('https://example.com/slow', ['timeoutMs' => 30000]);

See also#