You are browsing the unmaintained documentation for old Nette 2.1. See documentation for current Nette.

URL Parser and Builder

The Url and UrlScript classes make it easy to manage, parse, and manipulate URLs.

Installation:

composer require nette/http

Url

The Nette\Http\Url class makes it easy to work with the URL and its individual components, which are outlined in this diagram:

scheme  user  password  host   port    path        query  fragment
  |      |      |        |      |       |            |       |
/--\   /--\ /------\ /-------\ /--\/----------\ /--------\ /----\
http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer
\______\__________________________/
    |               |
 hostUrl        authority

URL generation is intuitive:

use Nette\Http\Url;

$url = new Url;
$url->setScheme('https')
	->setHost('localhost')
	->setPath('/edit')
	->setQueryParameter('foo', 'bar');

echo $url; // 'https://localhost/edit?foo=bar'

You can also parse the URL and then manipulate it:

$url = new Url(
	'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer'
);

The following methods are available to get or change individual URL components:

Setter Getter Returned value
setScheme(string $scheme) getScheme(): string 'http'
setUser(string $user) getUser(): string 'john'
setPassword(string $password) getPassword(): string 'xyz*12'
setHost(string $host) getHost(): string 'nette.org'
setPort(int $port) getPort(): ?int 8080
setPath(string $path) getPath(): string '/en/download'
setQuery(string|array $query) getQuery(): string 'name=param'
setFragment(string $fragment) getFragment(): string 'footer'
  getAuthority(): string 'nette.org:8080'
  getHostUrl(): string 'http://nette.org:8080'
  getAbsoluteUrl(): string full URL

We can also operate with individual query parameters using:

Setter Getter
setQueryParameter(string $name, $val) getQueryParameter(string $name)

Method isEqual(string|Url $anotherUrl): bool tests whether the two URLs are identical.

$url->isEqual('https://nette.org');

UrlScript

The Nette\Http\UrlScript class is a descendant of Url and additionally distinguishes these logical parts of the URL:

     baseUrl    basePath  relativePath  relativeUrl
        |          |        |               |
/---------------/-----\/--------\---------------------------\
http://nette.org/admin/script.php/pathinfo/?name=param#footer
                \_______________/\________/
                       |              |
                  scriptPath       pathInfo

The following methods are available to get these parts:

Getter Returned value
getScriptPath(): string '/admin/script.php'
getBasePath(): string '/admin/'
getBaseUrl(): string 'http://nette.org/admin/'
getRelativePath(): string 'script.php'
getRelativeUrl(): string 'script.php/pathinfo/?name=param#footer'
getPathInfo(): string '/pathinfo/'

We do not create objects UrlScript directly, but the method Nette\Http\Request::getUrl() returns it.


Related blog posts