Core\Uri::scheme
$uri->scheme(): ?stringReturns the scheme of an address, which is the part before the first :. For https://example.com/, scheme() returns https. For mailto:ann@example.com, it returns mailto.
The scheme is returned as it was written, so HTTPS stays upper case. Schemes do not depend on case, so make the result lower case with Core\Str::lower before you compare it.
The result is null when the address has no scheme. A path such as /about or photo.jpg has no scheme. An address that starts with //, such as //cdn.example.com/logo.png, has no scheme too.
The examples below read the scheme of some addresses, tell a full address from a path, and accept a website link only when it uses http: or https:.
Return value
Returns ?string. The scheme, without the :. The result is null when the address has no scheme, such as /about or //example.com/.
Examples
Read the scheme
<?nvs// Shows how to read the scheme of an address, which is the part before the first `:`.
array<string> $addresses = [ 'https://example.com/', 'mailto:ann@example.com', 'ftp://files.example.com/report.pdf', 'HTTP://example.com/',];
// This prints https, mailto, ftp and HTTP.// The scheme is returned as it was written, so `HTTP` stays upper case.foreach ($addresses as string $address) { echo Core\Uri::parse($address)->scheme() as string, "\n";}httpsmailtoftpHTTPTell a full address from a path
<?nvs// Shows how `scheme` tells a full address from a path on the same site.
array<string> $links = ['https://example.com/help', '/help', '//cdn.example.com/logo.png', 'help.html'];
// `scheme` returns `null` when the address has no scheme.// This prints "full address" once and "no scheme" three times.foreach ($links as string $link) { if (Core\Uri::parse($link)->scheme() == null) { echo $link, ": no scheme\n"; } else { echo $link, ": full address\n"; }}https://example.com/help: full address/help: no scheme//cdn.example.com/logo.png: no schemehelp.html: no schemeAccept only web links
<?nvs// Shows how a profile page accepts a website link only when it starts with `http:` or `https:`.
class Profile{ public static function website(string $input): string { ?Core\Uri $link = Core\Uri::tryParse($input); if ($link == null) { return 'not saved'; } // A scheme can be written in upper case, so it is made lower case first. string $scheme = Core\Str::lower($link->scheme() ?? ''); if ($scheme != 'http' && $scheme != 'https') { return 'not saved'; } return 'saved ' . $link->toString(); }}
// This prints two saved links, then "not saved" three times.// A `javascript:` link would run code in the browser of every visitor.echo Profile::website('https://ann.example.com/'), "\n";echo Profile::website('HTTP://example.com/ann'), "\n";echo Profile::website('JavaScript:alert(1)'), "\n";echo Profile::website('/ann'), "\n";echo Profile::website('https://example.com/a b'), "\n";saved https://ann.example.com/saved HTTP://example.com/annnot savednot savednot saved