Parsing and building URLs with the Uri extension
suggest changePHP 8.5 added the Uri extension. It has two classes for working with URLs:
Uri\Rfc3986\Urifollows RFC 3986, the generic URI standard. It handles any scheme (https:,mailto:,urn:, your own) and relative references like../img/logo.png. It is strict: input that doesn't follow the grammar is rejected.Uri\WhatWg\Urlfollows the WHATWG URL Standard, which is how browsers parse URLs. It only accepts absolute URLs, fixes up sloppy input the way a browser would, and handles internationalized (IDN) host names.
Both classes are immutable value objects: you parse a string, read the components with getters, and get a modified copy from with*() methods. The extension is always enabled. It bundles its own parsers (uriparser and Lexbor), so you don't need intl or any other extension, even for IDN hosts.
This article covers parsing, validation errors, modifying and building URLs, resolving relative links, comparing URLs, and IDN hosts. All examples were run with PHP 8.5.
The older tools are covered in Parsing a URL, Using parse url, Build a URL-encoded query string from an array and Validate a URL. Web scraping uses Url::resolve() to follow links in a crawler.
Why not parse_url()
parse_url() doesn't implement any standard. It splits the string with its own rules and returns whatever pieces it found, so it accepts input that is not a URL and can disagree with browsers and HTTP clients about which host a URL points to:
<?php
// The host contains a port, and a space is accepted in a host name
print_r(parse_url('http://example.com:80:80/'));
print_r(parse_url('http://exa mple.com/'));
// Who is the host here?
print_r(parse_url('http://user@evil.com@good.com/'));
// Nothing is normalized
print_r(parse_url('HTTPS://EXAMPLE.com/a/../b'));
Output:
Array
(
[scheme] => http
[host] => example.com:80
[port] => 80
[path] => /
)
Array
(
[scheme] => http
[host] => exa mple.com
[path] => /
)
Array
(
[scheme] => http
[host] => good.com
[user] => user@evil.com
[path] => /
)
Array
(
[scheme] => HTTPS
[host] => EXAMPLE.com
[path] => /a/../b
)
The first URL is invalid, yet you get a host of example.com:80. The second has a space in the host. The third has an @ in the user name, which is not allowed, and other parsers may decide differently which part is the host. That difference is a classic source of SSRF and open-redirect bugs: you validate the host with one parser and send the request with another. And nothing is normalized, so HTTPS://EXAMPLE.com/a/../b and https://example.com/b look different although they are the same URL.
The PHP manual warns that parse_url() may give wrong results for relative or malformed URLs, and that its results may not match how HTTP clients behave. For new code, use one of the Uri classes.
Parsing a URL
Create the object with new and read the components with getters:
<?php
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$s = 'https://user:secret@Example.COM:8443/docs/../api/v1/%7Ekjk?sort=name&page=2#top';
$uri = new Uri($s);
echo $uri->getScheme(), "\n";
echo $uri->getUsername(), ' / ', $uri->getPassword(), "\n";
echo $uri->getHost(), "\n";
echo $uri->getPort(), "\n";
echo $uri->getPath(), "\n";
echo $uri->getQuery(), "\n";
echo $uri->getFragment(), "\n";
echo $uri->toString(), "\n";
$url = new Url($s);
echo $url->getAsciiHost(), "\n";
echo $url->getPath(), "\n";
echo $url->toAsciiString(), "\n";
Output:
https
user / secret
example.com
8443
/api/v1/~kjk
sort=name&page=2
top
https://user:secret@example.com:8443/api/v1/~kjk?sort=name&page=2#top
example.com
/api/v1/%7Ekjk
https://user:secret@example.com:8443/api/v1/%7Ekjk?sort=name&page=2#top
The getters are getScheme(), getUsername(), getPassword(), getHost(), getPort(), getPath(), getQuery() and getFragment(). Uri also has getUserInfo() (user:secret). Url has getAsciiHost() and getUnicodeHost() instead of getHost(), covered in the IDN hosts section below.
Both classes lowercase the scheme and host and remove . and .. segments from the path. They differ in percent-encoding: Uri decodes encoded characters that don't need encoding (%7E becomes ~), while Url leaves them as they are.
Normalized and raw components
Uri\Rfc3986\Uri gives you two versions of each component. The normal getters return the normalized value. The getRaw*() getters return exactly what was in the input:
<?php
use Uri\Rfc3986\Uri;
$uri = new Uri('https://Example.COM/docs/../api/%7Ekjk%2Fx?q=caf%C3%A9');
printf("%-6s %-20s %s\n", 'part', 'normalized', 'raw');
printf("%-6s %-20s %s\n", 'host', $uri->getHost(), $uri->getRawHost());
printf("%-6s %-20s %s\n", 'path', $uri->getPath(), $uri->getRawPath());
printf("%-6s %-20s %s\n", 'query', $uri->getQuery(), $uri->getRawQuery());
echo $uri->toString(), "\n";
echo $uri->toRawString(), "\n";
Output:
part normalized raw
host example.com Example.COM
path /api/~kjk%2Fx /docs/../api/%7Ekjk%2Fx
query q=caf%C3%A9 q=caf%C3%A9
https://example.com/api/~kjk%2Fx?q=caf%C3%A9
https://Example.COM/docs/../api/%7Ekjk%2Fx?q=caf%C3%A9
Only unreserved characters are decoded. %2F stays encoded because a decoded / would change the path structure, and %C3%A9 stays encoded because non-ASCII characters must be encoded in a URI. To get the human-readable text of a component, decode it yourself with rawurldecode().
toString() returns the normalized URI and toRawString() returns the original. Url has no raw getters because the WHATWG parser always normalizes. Its string methods are toAsciiString() and toUnicodeString().
Missing components
A missing component is null, but an empty path is an empty string. The two classes don't agree on all of them:
<?php
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$uri = new Uri('https://example.com');
var_dump($uri->getPort(), $uri->getPath(), $uri->getQuery());
$url = new Url('https://example.com');
var_dump($url->getPort(), $url->getPath(), $url->getQuery());
$url = new Url('https://example.com:443/');
var_dump($url->getPort());
Output:
NULL
string(0) ""
NULL
NULL
string(1) "/"
NULL
NULL
Url always has a path, / for http(s) URLs. It also treats the scheme's default port (80 for http, 443 for https) as no port. Uri knows nothing about schemes: for RFC 3986, :443 is just a port number, and an empty path is fine.
Validation and errors
Uri::parse() and Url::parse() return null for invalid input. The constructors throw. Here is how the two parsers treat a few inputs:
<?php
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$inputs = [
'http://example.com:80:80/',
'http://exa mple.com/',
'/a b?x=1',
'http://example.com:99999/',
'http://1.2.3.256/',
'../img/logo.png',
];
foreach ($inputs as $s) {
printf("%-28s rfc3986: %-26s whatwg: %s\n",
$s,
Uri::parse($s)?->toString() ?? 'null',
Url::parse($s)?->toAsciiString() ?? 'null');
}
Output:
http://example.com:80:80/ rfc3986: null whatwg: null
http://exa mple.com/ rfc3986: null whatwg: null
/a b?x=1 rfc3986: null whatwg: null
http://example.com:99999/ rfc3986: http://example.com:99999/ whatwg: null
http://1.2.3.256/ rfc3986: http://1.2.3.256/ whatwg: null
../img/logo.png rfc3986: ../img/logo.png whatwg: null
Neither class accepts the inputs that fooled parse_url(). The differences come from the standards. RFC 3986 only checks syntax: a port is any sequence of digits and 1.2.3.256 is a valid registered name. The WHATWG parser checks that the port fits in 16 bits and that a host made of numbers is a valid IPv4 address. It also rejects relative references, because a browser URL is always absolute.
Exceptions
The constructors throw Uri\InvalidUriException. For Url it's the subclass Uri\WhatWg\InvalidUrlException, whose $errors property lists what went wrong as Uri\WhatWg\UrlValidationError objects:
<?php
use Uri\InvalidUriException;
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
try {
new Uri('http://exa mple.com/');
} catch (InvalidUriException $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
try {
new Url('http://example.com:99999/');
} catch (InvalidUriException $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
foreach ($e->errors as $error) {
echo $error->type->name, ' at "', $error->context, '"',
$error->failure ? ' (failure)' : '', "\n";
}
}
Output:
Uri\InvalidUriException: The specified URI is malformed
Uri\WhatWg\InvalidUrlException: The specified URI is malformed (PortOutOfRange)
PortOutOfRange at "/" (failure)
Each UrlValidationError has three read-only properties: type (a Uri\WhatWg\UrlValidationErrorType enum case), context (the rest of the input where the parser was when it found the problem) and failure. Catch Uri\InvalidUriException if you want to handle both classes the same way. Both exception classes extend Uri\UriException, which extends Exception.
Soft errors
The WHATWG standard separates errors that make parsing fail from errors that the parser fixes up. A browser accepts https:example.com and a space in a path, but the standard still calls them validation errors. Url::parse() reports both kinds through its third parameter, passed by reference. The constructor's equivalent is $softErrors:
<?php
use Uri\WhatWg\Url;
foreach (['https:example.com/x', 'http://0x7f.1/', 'relative/path'] as $s) {
$url = Url::parse($s, null, $errors);
echo $s, ' => ', $url?->toAsciiString() ?? 'null', "\n";
foreach ($errors as $error) {
echo ' ', $error->type->name, $error->failure ? ' (failure)' : '', "\n";
}
}
// The constructor reports soft errors through its third parameter
$url = new Url('https://example.com/my report.pdf', softErrors: $soft);
echo $url->toAsciiString(), ' (', count($soft), " soft error)\n";
echo $soft[0]->type->name, "\n";
Output:
https:example.com/x => https://example.com/x
SpecialSchemeMissingFollowingSolidus
http://0x7f.1/ => http://127.0.0.1/
Ipv4NonDecimalPart
relative/path => null
MissingSchemeNonRelativeUrl (failure)
https://example.com/my%20report.pdf (1 soft error)
InvalidUrlUnit
The URL is fixed and the problem is reported. An error with failure set to false is a soft error. In the last example the parser percent-encoded the space and parsing went on. Log soft errors, or reject the URL if it comes from a source that should produce clean URLs.
Validating user input
For "is this a web address I'm willing to fetch?", parse it, then check the parts you care about. Parsing alone isn't enough, because javascript:alert(1) and mailto: addresses are valid URIs:
<?php
use Uri\Rfc3986\Uri;
function isHttpUrl(string $input): bool
{
$uri = Uri::parse($input);
return $uri !== null
&& in_array($uri->getScheme(), ['http', 'https'], true)
&& ($uri->getHost() ?? '') !== '';
}
foreach (['https://example.com/a', 'HTTP://Example.com', 'javascript:alert(1)',
'ftp://example.com/', '//example.com/', 'http:///path', 'not a url'] as $s) {
printf("%-24s %s\n", $s, isHttpUrl($s) ? 'ok' : 'rejected');
}
Output:
https://example.com/a ok
HTTP://Example.com ok
javascript:alert(1) rejected
ftp://example.com/ rejected
//example.com/ rejected
http:///path rejected
not a url rejected
Check the scheme after parsing, not with string functions on the input. getScheme() is already lowercased, so HTTP:// passes. An http:///path URI parses (with an empty host), so check the host as well. If the URL will be opened by a browser, Url::parse() is the better choice for this check, because it parses the same way the browser will.
Modifying URLs with with*() methods
Every component has a with*() method: withScheme(), withUsername(), withPassword(), withHost(), withPort(), withPath(), withQuery() and withFragment() (Uri has withUserInfo() instead of separate user name and password methods). The object is never changed. Each call returns a new object, so you can chain them and keep the original:
<?php
use Uri\Rfc3986\Uri;
$base = new Uri('https://api.example.com/v1/users?page=1');
$next = $base->withQuery('page=2')->withFragment('results');
$local = $base
->withScheme('http')
->withHost('localhost')
->withPort(8080)
->withQuery(null);
echo $base->toString(), "\n";
echo $next->toString(), "\n";
echo $local->toString(), "\n";
Output:
https://api.example.com/v1/users?page=1
https://api.example.com/v1/users?page=2#results
http://localhost:8080/v1/users
Pass null to remove an optional component. withPath() takes a string, because a URI always has a path, even an empty one.
The two classes validate new values differently. Uri wants an already encoded, valid component and throws InvalidUriException otherwise. Url works like setting url.pathname in JavaScript: it encodes what needs encoding, adds the leading /, and strips a leading ? from a query:
<?php
use Uri\InvalidUriException;
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$uri = new Uri('https://api.example.com/v1/users');
$url = new Url('https://api.example.com/v1/users');
$changes = [
'withHost("exa mple.com")' => fn($u) => $u->withHost('exa mple.com'),
'withPath("/my files")' => fn($u) => $u->withPath('/my files'),
'withPath("users")' => fn($u) => $u->withPath('users'),
'withQuery("q=żółw")' => fn($u) => $u->withQuery('q=żółw'),
'withQuery("?a=1")' => fn($u) => $u->withQuery('?a=1'),
];
foreach ($changes as $label => $change) {
echo $label, "\n";
foreach (['rfc3986' => $uri, 'whatwg' => $url] as $name => $obj) {
try {
$new = $change($obj);
$str = $new instanceof Url ? $new->toAsciiString() : $new->toString();
} catch (InvalidUriException $e) {
$str = $e->getMessage();
}
printf(" %-8s %s\n", $name, $str);
}
}
Output:
withHost("exa mple.com")
rfc3986 The specified host is malformed
whatwg The specified host is malformed (DomainInvalidCodePoint)
withPath("/my files")
rfc3986 The specified path is malformed
whatwg https://api.example.com/my%20files
withPath("users")
rfc3986 The specified path is malformed
whatwg https://api.example.com/users
withQuery("q=żółw")
rfc3986 The specified query is malformed
whatwg https://api.example.com/v1/users?q=%C5%BC%C3%B3%C5%82w
withQuery("?a=1")
rfc3986 https://api.example.com/v1/users??a=1
whatwg https://api.example.com/v1/users?a=1
Note the ??a=1: in RFC 3986 a ? is a valid character inside a query, so Uri keeps it. The query you pass to withQuery() doesn't include the leading ?.
Url also follows the browser rules for schemes and ports. It ignores a change that the WHATWG standard doesn't allow, without an error:
<?php
use Uri\WhatWg\Url;
$url = new Url('https://example.com/');
// Switching between a "special" scheme and a non-special one is ignored
echo $url->withScheme('ftp')->toAsciiString(), "\n";
echo $url->withScheme('mailto')->toAsciiString(), "\n";
// The default port for the scheme is dropped
var_dump($url->withPort(443)->getPort());
echo $url->withPort(8443)->toAsciiString(), "\n";
Output:
ftp://example.com/
https://example.com/
NULL
https://example.com:8443/
Working with query parameters
Neither class parses the query into parameters. getQuery() returns a string. Use parse_str() to split it and http_build_query() to build a new one, then pass the result to withQuery():
<?php
use Uri\Rfc3986\Uri;
function withQueryParams(Uri $uri, array $params): Uri
{
parse_str($uri->getRawQuery() ?? '', $current);
$merged = array_merge($current, $params);
// null removes a parameter (http_build_query skips nulls)
$query = http_build_query($merged, encoding_type: PHP_QUERY_RFC3986);
return $uri->withQuery($query === '' ? null : $query);
}
$uri = new Uri('https://shop.example.com/search?q=lamp&page=3&sort=price');
echo withQueryParams($uri, ['page' => 4])->toString(), "\n";
echo withQueryParams($uri, ['q' => 'desk lamp & shade', 'page' => null])->toString(), "\n";
echo withQueryParams($uri, ['q' => null, 'page' => null, 'sort' => null])->toString(), "\n";
parse_str($uri->getQuery(), $params);
print_r($params);
Output:
https://shop.example.com/search?q=lamp&page=4&sort=price
https://shop.example.com/search?q=desk%20lamp%20%26%20shade&sort=price
https://shop.example.com/search
Array
(
[q] => lamp
[page] => 3
[sort] => price
)
PHP_QUERY_RFC3986 makes http_build_query() encode spaces as %20 rather than +, which Uri accepts as a valid query. parse_str() decodes both. Parse the raw query when you rebuild it, so encoded characters like %26 (&) aren't decoded and lost. See Build a URL-encoded query string from an array for the details of http_build_query().
Resolving relative links
resolve() turns a reference such as a link's href into an absolute URL, relative to the object you call it on. It follows the RFC 3986 algorithm for Uri and the browser algorithm for Url:
<?php
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$page = 'https://example.com/blog/2025/post.html?lang=en#comments';
$uri = new Uri($page);
$url = new Url($page);
$links = ['other.html', '../archive/', '/about', '?lang=pl', '#top',
'//cdn.example.net/app.js', 'https://php.net/', '../../../../x'];
foreach ($links as $href) {
printf("%-26s %s\n", $href, $uri->resolve($href)->toString());
}
// The WHATWG resolver gives the same results and also accepts what browsers accept
echo $url->resolve('my notes.html')->toAsciiString(), "\n";
echo $url->resolve('..\img\logo.png')->toAsciiString(), "\n";
try {
$uri->resolve('my notes.html');
} catch (\Uri\InvalidUriException $e) {
echo $e->getMessage(), "\n";
}
Output:
other.html https://example.com/blog/2025/other.html
../archive/ https://example.com/blog/archive/
/about https://example.com/about
?lang=pl https://example.com/blog/2025/post.html?lang=pl
#top https://example.com/blog/2025/post.html?lang=en#top
//cdn.example.net/app.js https://cdn.example.net/app.js
https://php.net/ https://php.net/
../../../../x https://example.com/x
https://example.com/blog/2025/my%20notes.html
https://example.com/blog/img/logo.png
The specified URI is malformed
A fragment-only reference keeps the query, a query-only reference keeps the path, and a protocol-relative //host reference keeps the scheme. Too many ../ segments stop at the root. This is the code you need to follow links in a crawler. Joining strings with dirname() gets these cases wrong.
HTML found on the web often contains links with spaces or backslashes. Browsers accept them, so use Url to resolve links found on web pages.
You can also pass the base URL as the second argument of the constructor or parse():
<?php
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$base = new Url('https://example.com/docs/');
echo (new Url('img/logo.png', $base))->toAsciiString(), "\n";
echo Uri::parse('img/logo.png', new Uri('https://example.com/docs/'))->toString(), "\n";
// A relative reference on its own is a valid RFC 3986 URI, but it can't be a base
$rel = new Uri('../img/logo.png?v=2');
var_dump($rel->getScheme(), $rel->getHost(), $rel->getPath());
try {
$rel->resolve('other.png');
} catch (\Uri\InvalidUriException $e) {
echo $e->getMessage(), "\n";
}
Output:
https://example.com/docs/img/logo.png
https://example.com/docs/img/logo.png
NULL
NULL
string(15) "../img/logo.png"
The specified base URI must be absolute
A relative reference parsed with Uri has no scheme and no host. You can inspect it, but you can't resolve other references against it.
Comparing URLs
equals() compares the normalized forms of two URLs of the same class. By default it ignores the fragment, because #section doesn't change which resource a URL identifies:
<?php
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$pairs = [
['https://example.com/a/b', 'HTTPS://EXAMPLE.COM/a/./x/../b'],
['https://example.com/~kjk', 'https://example.com/%7Ekjk'],
['https://example.com/a%2fb', 'https://example.com/a%2Fb'],
['https://example.com/', 'https://example.com:443/'],
['https://example.com', 'https://example.com/'],
['https://example.com/p#a', 'https://example.com/p#b'],
['https://example.com/?a=1&b=2', 'https://example.com/?b=2&a=1'],
];
printf("%-30s %-32s %-8s %s\n", 'a', 'b', 'rfc3986', 'whatwg');
foreach ($pairs as [$a, $b]) {
printf("%-30s %-32s %-8s %s\n", $a, $b,
var_export((new Uri($a))->equals(new Uri($b)), true),
var_export((new Url($a))->equals(new Url($b)), true));
}
Output:
a b rfc3986 whatwg
https://example.com/a/b HTTPS://EXAMPLE.COM/a/./x/../b true true
https://example.com/~kjk https://example.com/%7Ekjk true false
https://example.com/a%2fb https://example.com/a%2Fb true false
https://example.com/ https://example.com:443/ false true
https://example.com https://example.com/ false true
https://example.com/p#a https://example.com/p#b true true
https://example.com/?a=1&b=2 https://example.com/?b=2&a=1 false false
Each class normalizes by its own standard. Uri decodes unreserved characters and normalizes the case of percent-encoding, but knows nothing about default ports and doesn't add a / path. Url does the opposite. Neither reorders query parameters, because the order of parameters can matter to the server.
Pass Uri\UriComparisonMode::IncludeFragment to compare fragments too:
<?php
use Uri\UriComparisonMode;
use Uri\WhatWg\Url;
$a = new Url('https://example.com/page#intro');
$b = new Url('https://example.com/page#usage');
var_dump($a->equals($b));
var_dump($a->equals($b, UriComparisonMode::IncludeFragment));
// Don't use == on URI objects
var_dump(new Url('https://example.com/') == new Url('https://php.net/'));
Output:
bool(true)
bool(false)
bool(true)
The last line is a trap. The objects keep their data internally and have no PHP properties, so == compares two empty property lists and returns true for any two URLs of the same class. Always compare with equals() (or compare toString() results).
IDN hosts
A host can contain non-ASCII characters, like bücher.example. In DNS and HTTP it is sent in its ASCII form, called Punycode: xn--bcher-kva.example. Url converts in both directions:
<?php
use Uri\WhatWg\Url;
$url = new Url('https://Bücher.example/straße?q=żółw');
echo $url->getAsciiHost(), "\n";
echo $url->getUnicodeHost(), "\n";
echo $url->toAsciiString(), "\n";
echo $url->toUnicodeString(), "\n";
$puny = new Url('https://xn--bcher-kva.example/stra%C3%9Fe?q=%C5%BC%C3%B3%C5%82w');
var_dump($url->equals($puny));
// A Cyrillic "а" looks like a Latin "a" but is a different host
echo (new Url('https://аpple.com/'))->getAsciiHost(), "\n";
Output:
xn--bcher-kva.example
bücher.example
https://xn--bcher-kva.example/stra%C3%9Fe?q=%C5%BC%C3%B3%C5%82w
https://bücher.example/stra%C3%9Fe?q=%C5%BC%C3%B3%C5%82w
bool(true)
xn--pple-43d.com
Use toAsciiString() and getAsciiHost() for HTTP requests, DNS lookups, logs and comparisons. Use toUnicodeString() only to show the URL to a person. Only the host is converted: the path and query stay percent-encoded in both strings.
The Punycode form also shows homograph attacks. аpple.com above starts with a Cyrillic letter, and its ASCII host xn--pple-43d.com makes the difference obvious. Show the ASCII host when you ask users to confirm a domain.
Uri\Rfc3986\Uri doesn't support IDN. RFC 3986 only allows ASCII, so a raw non-ASCII host is rejected, and a percent-encoded one stays encoded:
<?php
use Uri\Rfc3986\Uri;
try {
new Uri('https://Bücher.example/');
} catch (\Uri\InvalidUriException $e) {
echo $e->getMessage(), "\n";
}
$uri = new Uri('https://b%C3%BCcher.example/');
echo $uri->getHost(), "\n";
Output:
The specified URI is malformed
b%C3%BCcher.example
Strings, JSON and serialization
The classes don't implement Stringable, so a URL object can't be used where a string is expected. Call toString() or toAsciiString() explicitly. json_encode() gives an empty object for the same reason. serialize() works and keeps the URL string:
<?php
use Uri\WhatWg\Url;
$url = new Url('https://example.com/a?b=1');
echo "Link: {$url->toAsciiString()}\n";
echo json_encode($url), "\n";
echo json_encode(['url' => $url->toAsciiString()], JSON_UNESCAPED_SLASHES), "\n";
$copy = unserialize(serialize($url));
var_dump($copy->equals($url));
try {
echo "Link: $url\n";
} catch (\Error $e) {
echo $e->getMessage(), "\n";
}
Output:
Link: https://example.com/a?b=1
{}
{"url":"https://example.com/a?b=1"}
bool(true)
Object of class Uri\WhatWg\Url could not be converted to string
Both classes are final and readonly, so you can't extend them. To add your own behaviour, such as an "allowed hosts" check, wrap the object in your own class, or write functions that take a Uri or Url parameter.
Which class to use
| Use case | Class |
|---|---|
| URLs that come from or go to browsers: links in HTML, redirects, user input | Uri\WhatWg\Url |
| Hosts with non-ASCII characters | Uri\WhatWg\Url |
Non-web schemes (urn:, mailto:, ldap:, custom app schemes) |
Uri\Rfc3986\Uri (works with Url too, without normalization) |
| Relative references as values on their own | Uri\Rfc3986\Uri |
| Strict validation for APIs and protocols specified with RFC 3986 | Uri\Rfc3986\Uri |
| Access to the original, unnormalized components | Uri\Rfc3986\Uri (getRaw*()) |
Don't mix the two for the same value. Validating a URL with one parser and using it with another brings back the problem parse_url() has. The classes don't convert into each other. To convert, pass the string from toString() or toAsciiString() to the other class.
Summary
- PHP 8.5's Uri extension is always available.
Uri\Rfc3986\Uriimplements RFC 3986, andUri\WhatWg\Urlimplements the browser URL standard. - Prefer them to
parse_url(), which follows no standard, accepts invalid URLs and doesn't normalize. newthrowsUri\InvalidUriException(forUrl,Uri\WhatWg\InvalidUrlExceptionwith an$errorsarray).parse()returnsnull.Urlreports soft errors through a by-reference parameter.- Objects are immutable:
with*()methods return modified copies.Urirejects invalid component values.Urlencodes them like a browser would. - There is no query parameter API. Use
parse_str()andhttp_build_query(..., encoding_type: PHP_QUERY_RFC3986)withwithQuery(). resolve()turns relative links into absolute URLs correctly. UseUrlfor links scraped from HTML.- Compare with
equals(), never with==, which is true for any two URLs. Fragments are ignored unless you passUriComparisonMode::IncludeFragment. Urlconverts IDN hosts withgetAsciiHost()/getUnicodeHost()andtoAsciiString()/toUnicodeString().Urionly accepts ASCII.