Skip to content

Core\Http\Client::head

Sends a HEAD request to another server and returns its status and headers.

A HEAD request is the same as a GET request, but the server sends no body. You use it to learn whether a page or a file exists, or how large a file is, without downloading it. The result is a Core\Http\Response: status() gives the status code, header() gives one header, and the body is always empty.

The URL is checked before anything is sent. Any public host is allowed, unless net.connect in [capabilities.net] in nvs.toml lists the allowed hosts. An address inside your own network throws a RuntimeError. Loopback (127.0.0.1) is allowed only from the command line and in development mode. connectTimeout limits the wait for the connection, and deadline limits the whole request.

Good to know: the examples run without a network, so every request in them throws an error before it is sent. They show one address that is not allowed, the time limit for connecting, and a link checker for a blog.

Parameters

  • $urlstring|Core\Http\TargetWhere the request goes. It is a URL that the program wrote, or a Core\Http\Target from Core\Http::allowUrl. A tainted URL comes from outside the program, such as from a request. It is not allowed here. Check it with Core\Http::allowUrl first.

Options

  • deadlineCore\Time\DurationoptionalThe time limit for the whole call. It covers the connection, every redirect, every retry and every wait between retries. If it is not given, the runtime's [http.client] deadline is used. There is no way to write a call with no deadline.
  • connectTimeoutCore\Time\DurationoptionalHow long the connection alone may take. This time is part of deadline, and is not added to it.
  • headersarray<secret string>optionalExtra request headers, by name. A secret value is a value the program must keep hidden, such as an API key. It is allowed here, because a credential must reach the API it is for. A tainted value is not allowed. The runtime adds its own headers as well.
  • followRedirectsuintoptionalHow many redirects to follow. If it is not given, the runtime's [http.client] max_redirects is used, and its default is 0. Each redirect is checked against the outbound policy again, and its address is approved again.
  • retryAttemptsuintoptionalThe total number of attempts, including the first. The default is 1, which means no retry. 0 throws an error. All attempts share one deadline, and retryBackoff sets the wait between them.
  • retryBackoffCore\Time\DurationoptionalThe base delay between retries. The delay doubles after each retry. Each wait is a random time up to that delay, which is called full jitter. If it is not given, it is 100ms.
  • retryIdempotencyKeystringoptionalSent as the Idempotency-Key header, with the same value on every attempt. It is required for post and patch when retryAttempts is given. Every other method also accepts it.
  • jsonmixedoptionalThe value to send as application/json. It is encoded once for the whole call. A secret inside it is sent, as it is in a header. A null value sends the JSON document null, not an empty body.
  • formarray<secret tainted string>optionalThe fields to send as application/x-www-form-urlencoded, by name.
  • bodysecret tainted string|secret tainted bytes|Core\Http\PartoptionalThe bytes to send exactly as given, with the media type in contentType. Only one of json, form, body and multipart may be given. A call that gives two of them does not compile. A call to get or head that gives one of them does not compile either.
  • contentTypestringoptionalThe media type of body. It has no effect without body, so giving it alone is a compile error.
  • multipartarray<secret tainted string|Core\Http\Part>optionalThe parts to send as multipart/form-data, by name.
  • identityCore\Http\IdentityoptionalThe client certificate to send when the server asks for one. Create it with Core\Http\Identity::read. Nothing is sent to a server that does not ask. Two different identities never share a pooled connection. A call without an identity does not share one with a call that has one.
  • tlsCastringoptionalThe PEM certificates to trust for this call. They replace [tls.client] roots certificates. The URL's host must be in the anchors grant of capabilities.tls. If it is not, the call throws an error before it connects.
  • tlsPinstring|array<string>optionalOne sha256//<base64> public-key pin, or several. The server is accepted if the hash of its SubjectPublicKeyInfo matches one of them. No certificate chain is checked. Use this to reach a server with a self-signed certificate. The host must be in the pin grant.
  • tlsVerifyHostbooloptionalIf it is false, the chain is still checked, and only the name check is skipped. The host must be in the any_name grant.
  • tlsVerifybooloptionalIf it is false, neither the chain nor the name is checked. The handshake signature is still checked, so the server has the key it sent. But nothing shows whose key it is. The host must be in the insecure grant.
  • tlsMinVersionstringoptionalThe lowest TLS version this call allows, "1.2" or "1.3". It needs no grant, because it can only make the call stricter. A value below the runtime's [tls.client] min_version throws an error.
  • connectTostringoptionalThe IP address to connect to. The URL's host is not looked up, but the certificate is still checked against that host. The host must be in the net.connect_to grant. The deployment's address policy checks this address like a looked-up one. With a Core\Http\Target as the URL, this option throws an error, because the target already has its approved addresses.
  • redirectToHttpbooloptionalIf it is true, a redirect from https to plain http may be followed. The redirect's host must also be in the net.downgrade grant. If it is not given, such a redirect throws an error. So a server cannot turn off a call's TLS with one Location header. This option does not affect a plain http URL that you request directly.

Return value

Returns Core\Http\Response. A Core\Http\Response with the status and the headers of the reply. Its body is empty. A 404 or a 500 is a normal reply and is returned here. Only a request that gets no reply at all throws an error. An https URL is fetched over TLS. The certificate is checked against the certificate authorities in [tls.client] roots.

Errors

  • RuntimeErrorThe URL is not allowed. It is not a URL, its scheme is not http or https, or it has no host. Or net.connect does not grant the host. Or the host resolves to a loopback, private, link-local or unspecified address that net.internal does not list. An option is out of range. A deadline, connectTimeout or retryBackoff is not a positive duration. Or retryAttempts is zero. A header name or value contains a control byte, which would end the line early. An https server sent a certificate that does not verify against [tls.client] roots, or against tlsCa when it is given. Or the certificate is not valid for that name. For these two cases, the message says which setting fixes it. Or the reply is not HTTP, or it is larger than the limit for one request.
  • TimeoutErrorThe deadline passed before the reply arrived. It covers the connection, every redirect, every retry and every wait between retries. If a wait would end after the deadline, the error is thrown at once, without waiting.
  • IOErrorThe last attempt could not connect to the approved address. Or the connection failed while the request was sent or the reply was read.

Examples

The examples below run with this configuration file.

nvs.toml
# The program may connect to public hosts only.
# `internal = []` allows no address on this computer or on a private network.
[capabilities.net]
internal = []

Checking a file without downloading it

<?nvs
// Shows how to ask whether a file exists without downloading it. A `HEAD` request
// returns the status and the headers, and never a body.
// 192.168.0.10 is a private address, so the call throws a `RuntimeError` before it sends anything.
try {
Core\Http\Response $response = Core\Http\Client::head('http://192.168.0.10/files/report.pdf');
echo 'status: ', $response->status(), ', size: ', $response->header('content-length') ?? 'unknown', "\n";
} catch (RuntimeError $refused) {
echo $refused->message, "\n";
}
Output
Core\Http\Client::head cannot connect to 192.168.0.10: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
help: add `internal = ["192.168.0.10"]` under `[capabilities.net]` in nvs.toml

A time limit for connecting

<?nvs
// Shows the option that limits how long a `HEAD` request may wait for the
// connection to the server.
// `connectTimeout` is the most time the connection may take. It must be longer
// than zero, so this call throws a `RuntimeError`.
try {
var $quick = Core\Http\Client::head('https://203.0.113.10/report.pdf', { connectTimeout: 0s });
} catch (RuntimeError $tooShort) {
echo $tooShort->message, "\n";
}
Output
Core\Http\Client::head: `connectTimeout` must be a positive duration, and this one is 0ns

A link checker

<?nvs
// Shows a link checker for a blog. It sends a `HEAD` request to each link, so it
// learns whether the page is there without downloading it.
array<string> $links = [
'http://192.168.0.10/posts/hello',
'http://10.1.2.3/images/cat.png',
'http://[fd00::5]/about',
];
uint $working = 0;
uint $broken = 0;
foreach ($links as string $link) {
try {
Core\Http\Response $response = Core\Http\Client::head($link, { deadline: 5s });
// A status below 400 means the page is there.
if ($response->status() < 400) {
$working = $working + 1;
} else {
echo 'broken: ', $link, ' (', $response->status(), ')', "\n";
$broken = $broken + 1;
}
} catch (RuntimeError $error) {
echo 'not checked: ', $error->message, "\n";
$broken = $broken + 1;
}
}
// All three links are private addresses, so this prints `working: 0, broken: 3`.
echo 'working: ', $working, ', broken: ', $broken, "\n";
Output
not checked: Core\Http\Client::head cannot connect to 192.168.0.10: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
help: add `internal = ["192.168.0.10"]` under `[capabilities.net]` in nvs.toml
not checked: Core\Http\Client::head cannot connect to 10.1.2.3: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
help: add `internal = ["10.1.2.3"]` under `[capabilities.net]` in nvs.toml
not checked: Core\Http\Client::head cannot connect to fd00::5: it is private (fc00::/7), which `net.internal` does not except
help: add `internal = ["fd00::5"]` under `[capabilities.net]` in nvs.toml
working: 0, broken: 3