Skip to content

Core\Uri::host

$uri->host(): ?string

Returns the host of an address. The host is the name of the server, such as example.com in https://example.com/cart.

$uri->host() returns the host as it was written. Upper-case letters stay upper case, so use Core\Str::lower before you compare two hosts. An IPv6 address keeps its brackets, such as [::1]. The port is not part of the host.

The result is null when the address has no // part, such as the link /docs/start. The result is "" when the // part is empty, as in file:///tmp/notes.txt.

The examples below read the host of a link, show the null and "" results, and check that a redirect only goes to your own site.

Return value

Returns ?string. The host. The result is null when the address has no // part. It is "" when the // part is empty, as in file:///tmp.

Examples

The server in a link

<?nvs
// Shows how to read the host of an address.
var $link = Core\Uri::parse('https://shop.example.com:8443/cart?item=42');
// The host is the name of the server, without the port. This prints shop.example.com.
echo $link->host(), "\n";
// The host is returned as it was written. This prints Example.COM.
echo Core\Uri::parse('http://Example.COM/')->host(), "\n";
Output
shop.example.com
Example.COM

No host and an empty host

<?nvs
// Shows the three kinds of result that `host` returns.
// A link that starts with one `/` has no host. The result is `null`, so this prints none.
echo Core\Uri::parse('/docs/start')->host() ?? 'none', "\n";
// A file address has an empty `//` part. The result is "", so this prints "".
echo "\"", Core\Uri::parse('file:///tmp/notes.txt')->host(), "\"\n";
// An IPv6 address keeps its brackets. This prints [::1].
echo Core\Uri::parse('http://[::1]:8080/')->host(), "\n";
Output
none
""
[::1]

Allow redirects only to your own site

<?nvs
// Shows how a server checks that a redirect only goes to its own site.
class Redirect
{
public static function isSafe(string $target): bool
{
var $uri = Core\Uri::parse($target);
if ($uri->host() == null) {
// A link such as `/account` has no host and no scheme, so it stays on this site.
// A link such as `javascript:alert(1)` has a scheme, so it is not allowed.
return $uri->scheme() == null;
}
// Upper-case letters stay in the host, so `lower` is used before the comparison.
return Core\Str::lower($uri->host() as string) == 'example.com';
}
}
// In a real program, the target comes from the `next` value of a sign-in link.
array<string> $targets = [
'/account',
'https://Example.COM/orders',
'https://evil.example.net/',
'//evil.example.net/',
'javascript:alert(1)',
];
// This prints allowed twice, then blocked three times.
foreach ($targets as string $target) {
echo $target, ': ', Redirect::isSafe($target) ? 'allowed' : 'blocked', "\n";
}
Output
/account: allowed
https://Example.COM/orders: allowed
https://evil.example.net/: blocked
//evil.example.net/: blocked
javascript:alert(1): blocked