Core\Uri::port
$uri->port(): ?intReturns the port of an address as a number. The port is the number after the host, such as 8080 in http://localhost:8080/.
The result is null when the address has no port. $uri->port() does not fill in a default port, so for https://example.com/ the result is null and not 443. Use ?? to choose the port your program needs in that case. The result is also null when a : has no digits after it, as in http://example.com:/.
A port is always a number from 0 to 65535. Core\Uri::parse throws an error for a larger number, so port never returns one.
The examples below read a port, show when the result is null, and choose the port a program connects to.
Return value
Returns ?int. The port, from 0 to 65535. The result is null when the address has no port. It is also null when the : has no digits after it, as in http://example.com:/. A default port, such as 443 for https, is never filled in.
Examples
The port of a local server
<?nvs// Shows how to read the port of an address.
var $server = Core\Uri::parse('http://localhost:8080/health');
// The port is the number after the host. This prints 8080.echo $server->port(), "\n";
// The result is a number, so you can calculate with it. This prints 8081.echo ($server->port() ?? 0) + 1, "\n";80808081No port is null
<?nvs// Shows when `port` returns `null`.
// No port is written. The default port 443 is not filled in, so this prints none.echo Core\Uri::parse('https://example.com/')->port() ?? 'none', "\n";
// A `:` with no digits after it is not a port. This prints none.echo Core\Uri::parse('http://example.com:/')->port() ?? 'none', "\n";
// Zeros in front of the port are ignored. This prints 80.echo Core\Uri::parse('http://example.com:0080/')->port() ?? 'none', "\n";nonenone80The port to connect to
<?nvs// Shows how a program chooses the port it connects to, using the default port of the scheme.
class Target{ public static function port(Core\Uri $uri): int { ?int $written = $uri->port(); if ($written != null) { return $written as int; } // No port is written, so the default port of the scheme is used. if (Core\Str::lower($uri->scheme() ?? '') == 'https') { return 443; } return 80; }}
// In a real program, these addresses come from a configuration file.array<string> $services = [ 'https://api.example.com/v1', 'http://cache.example.com/', 'https://search.example.com:9200/',];
// This prints api.example.com:443, cache.example.com:80 and search.example.com:9200.foreach ($services as string $service) { var $uri = Core\Uri::parse($service); echo $uri->host(), ':', Target::port($uri), "\n";}api.example.com:443cache.example.com:80search.example.com:9200