namespace GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;
* PSR-7 URI implementation.
* @author Michael Dowling
* @author Tobias Schultze
* @author Matthew Weier O'Phinney
class Uri implements UriInterface
* Absolute http and https URIs require a host per RFC 7230 Section 2.7
* but in generic URIs the host can be empty. So for http(s) URIs
* we apply this default host when no host is given yet to form a
const HTTP_DEFAULT_HOST = 'localhost';
private static $defaultPorts = [
private static $charUnreserved = 'a-zA-Z0-9_\-\.~';
private static $charSubDelims = '!\$&\'\(\)\*\+,;=';
private static $replaceQuery = ['=' => '%3D', '&' => '%26'];
/** @var string Uri scheme. */
/** @var string Uri user info. */
/** @var string Uri host. */
/** @var int|null Uri port. */
/** @var string Uri path. */
/** @var string Uri query string. */
/** @var string Uri fragment. */
* @param string $uri URI to parse
public function __construct($uri = '')
// weak type check to also accept null until we can add scalar type hints
$parts = self::parse($uri);
throw new \InvalidArgumentException("Unable to parse URI: $uri");
$this->applyParts($parts);
* UTF-8 aware \parse_url() replacement.
* The internal function produces broken output for non ASCII domain names
* (IDN) when used with locales other than "C".
* On the other hand, cURL understands IDN correctly only when UTF-8 locale
* is configured ("C.UTF-8", "en_US.UTF-8", etc.).
* @see https://bugs.php.net/bug.php?id=52923
* @see https://www.php.net/manual/en/function.parse-url.php#114817
* @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING
private static function parse($url)
if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) {
$encodedUrl = preg_replace_callback(
static function ($matches) {
return urlencode($matches[0]);
$result = parse_url($prefix . $encodedUrl);
return array_map('urldecode', $result);
public function __toString()
return self::composeComponents(
* Composes a URI reference string from its various components.
* Usually this method does not need to be called manually but instead is used indirectly via
* `Psr\Http\Message\UriInterface::__toString`.
* PSR-7 UriInterface treats an empty component the same as a missing component as
* getQuery(), getFragment() etc. always return a string. This explains the slight
* difference to RFC 3986 Section 5.3.
* Another adjustment is that the authority separator is added even when the authority is missing/empty
* for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with
* `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But
* `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
* @param string $authority
* @param string $fragment
* @link https://tools.ietf.org/html/rfc3986#section-5.3
public static function composeComponents($scheme, $authority, $path, $query, $fragment)
// weak type checks to also accept null until we can add scalar type hints
if ($authority != ''|| $scheme === 'file') {
$uri .= '//' . $authority;
* Whether the URI has the default port of the current scheme.
* `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used
* independently of the implementation.
* @param UriInterface $uri
public static function isDefaultPort(UriInterface $uri)
return $uri->getPort() === null
|| (isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]);
* Whether the URI is absolute, i.e. it has a scheme.
* An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
* if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
* to another URI, the base URI. Relative references can be divided into several forms:
* - network-path references, e.g. '//example.com/path'
* - absolute-path references, e.g. '/path'
* - relative-path references, e.g. 'subpath'
* @param UriInterface $uri
* @see Uri::isNetworkPathReference
* @see Uri::isAbsolutePathReference
* @see Uri::isRelativePathReference
* @link https://tools.ietf.org/html/rfc3986#section-4
public static function isAbsolute(UriInterface $uri)
return $uri->getScheme() !== '';
* Whether the URI is a network-path reference.
* A relative reference that begins with two slash characters is termed an network-path reference.
* @param UriInterface $uri
* @link https://tools.ietf.org/html/rfc3986#section-4.2
public static function isNetworkPathReference(UriInterface $uri)
return $uri->getScheme() === '' && $uri->getAuthority() !== '';
* Whether the URI is a absolute-path reference.
* A relative reference that begins with a single slash character is termed an absolute-path reference.
* @param UriInterface $uri
* @link https://tools.ietf.org/html/rfc3986#section-4.2
public static function isAbsolutePathReference(UriInterface $uri)
return $uri->getScheme() === ''
&& $uri->getAuthority() === ''
&& isset($uri->getPath()[0])
&& $uri->getPath()[0] === '/';
* Whether the URI is a relative-path reference.
* A relative reference that does not begin with a slash character is termed a relative-path reference.
* @param UriInterface $uri
* @link https://tools.ietf.org/html/rfc3986#section-4.2
public static function isRelativePathReference(UriInterface $uri)
return $uri->getScheme() === ''
&& $uri->getAuthority() === ''
&& (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/');
* Whether the URI is a same-document reference.
* A same-document reference refers to a URI that is, aside from its fragment
* component, identical to the base URI. When no base URI is given, only an empty
* URI reference (apart from its fragment) is considered a same-document reference.
* @param UriInterface $uri The URI to check
* @param UriInterface|null $base An optional base URI to compare against
* @link https://tools.ietf.org/html/rfc3986#section-4.4
public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null)
$uri = UriResolver::resolve($base, $uri);
return ($uri->getScheme() === $base->getScheme())
&& ($uri->getAuthority() === $base->getAuthority())
&& ($uri->getPath() === $base->getPath())
&& ($uri->getQuery() === $base->getQuery());
return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === '';
* Removes dot segments from a path and returns the new path.
* @deprecated since version 1.4. Use UriResolver::removeDotSegments instead.
* @see UriResolver::removeDotSegments
public static function removeDotSegments($path)
return UriResolver::removeDotSegments($path);
* Converts the relative URI into a new URI that is resolved against the base URI.
* @param UriInterface $base Base URI
* @param string|UriInterface $rel Relative URI
* @deprecated since version 1.4. Use UriResolver::resolve instead.
* @see UriResolver::resolve
public static function resolve(UriInterface $base, $rel)
if (!($rel instanceof UriInterface)) {
return UriResolver::resolve($base, $rel);
* Creates a new URI with a specific query string value removed.
* Any existing query string values that exactly match the provided key are
* @param UriInterface $uri URI to use as a base.
* @param string $key Query string key to remove.
public static function withoutQueryValue(UriInterface $uri, $key)
$result = self::getFilteredQueryString($uri, [$key]);
return $uri->withQuery(implode('&', $result));
* Creates a new URI with a specific query string value.
* Any existing query string values that exactly match the provided key are
* removed and replaced with the given key value pair.
* A value of null will set the query string key without a value, e.g. "key"
* instead of "key=value".
* @param UriInterface $uri URI to use as a base.
* @param string $key Key to set.
* @param string|null $value Value to set
public static function withQueryValue(UriInterface $uri, $key, $value)
$result = self::getFilteredQueryString($uri, [$key]);
$result[] = self::generateQueryString($key, $value);
return $uri->withQuery(implode('&', $result));
* Creates a new URI with multiple specific query string values.
* It has the same behavior as withQueryValue() but for an associative array of key => value.
* @param UriInterface $uri URI to use as a base.
* @param array $keyValueArray Associative array of key and values
public static function withQueryValues(UriInterface $uri, array $keyValueArray)
$result = self::getFilteredQueryString($uri, array_keys($keyValueArray));
foreach ($keyValueArray as $key => $value) {
$result[] = self::generateQueryString($key, $value);
return $uri->withQuery(implode('&', $result));
* Creates a URI from a hash of `parse_url` components.
* @link http://php.net/manual/en/function.parse-url.php
* @throws \InvalidArgumentException If the components do not form a valid URI.
public static function fromParts(array $parts)
$uri->applyParts($parts);
public function getScheme()
public function getAuthority()
$authority = $this->host;
if ($this->userInfo !== '') {
$authority = $this->userInfo . '@' . $authority;
if ($this->port !== null) {
$authority .= ':' . $this->port;
public function getUserInfo()
public function getHost()
public function getPort()
public function getPath()
public function getQuery()
public function getFragment()
public function withScheme($scheme)
$scheme = $this->filterScheme($scheme);
if ($this->scheme === $scheme) {
$new->removeDefaultPort();
public function withUserInfo($user, $password = null)
$info = $this->filterUserInfoComponent($user);
if ($password !== null) {
$info .= ':' . $this->filterUserInfoComponent($password);
if ($this->userInfo === $info) {