PHPackages                             rowbot/url - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rowbot/url

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

rowbot/url
==========

A WHATWG URL spec compliant URL parser for working with URLs and their query strings.

4.1.0(8mo ago)19648.2k—1.4%[1 issues](https://github.com/TRowbotham/URL-Parser/issues)3MITPHPPHP &gt;=8.1CI passing

Since Feb 23Pushed 8mo ago3 watchersCompare

[ Source](https://github.com/TRowbotham/URL-Parser)[ Packagist](https://packagist.org/packages/rowbot/url)[ RSS](/packages/rowbot-url/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (11)Versions (24)Used By (3)

URL-Parser
==========

[](#url-parser)

[![GitHub](https://camo.githubusercontent.com/d49eb07c1b0de58aef3ed34ec7754512b941bf8512f39dafe8110aae816910cb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f54526f77626f7468616d2f55524c2d5061727365722e7376673f7374796c653d666c61742d737175617265)](https://github.com/TRowbotham/URL-Parser/blob/master/LICENSE)[![GitHub Workflow Status](https://camo.githubusercontent.com/e857bc58e5acf61a072b339b07e1f91a5037c9bc2380a6dda23d555a7d9fa066/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f54526f77626f7468616d2f55524c2d5061727365722f74657374732e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/TRowbotham/URL-Parser/actions)[![Codecov](https://camo.githubusercontent.com/87f7024d50f85e36658fdd662e117f23cb05309af52a895318cd9fc65cc3f42a/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f54526f77626f7468616d2f55524c2d5061727365722f6d61737465723f6c6f676f3d436f6465636f76267374796c653d666c61742d73717561726526746f6b656e3d574457466738776d6a57)](https://codecov.io/gh/TRowbotham/URL-Parser)[![Packagist](https://camo.githubusercontent.com/ad0955f4710de4b573d553ad59c3a334159f07d496ea209435fc73594c984aaa/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726f77626f742f75726c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rowbot/url)[![Packagist](https://camo.githubusercontent.com/4c5e67028eaaebbfd0b79f7f0fc7dc8e31d0bec239be1e6563359e3cba8c1d50/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f726f77626f742f75726c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rowbot/url)

A [WHATWG URL](https://url.spec.whatwg.org/) spec compliant URL parser for working with URLs and their query strings.

This API offers 2 objects that you can use to help you work with URLs; [URL](#url) and [URLSearchParams](#urlsearchparams).

Demo
----

[](#demo)

Checkout an interactive demo [here](https://url-demo.trowbotham.com/).

Requirements
------------

[](#requirements)

- PHP &gt;= 8.1
- `ext-mbstring`
- `brick/math`
- `rowbot/idna`

Installation
------------

[](#installation)

```
composer require rowbot/url
```

URL
---

[](#url)

The URL object is the primary object for working with a URL.

### The URL constructor

[](#the-url-constructor)

`URL(string|\Stringable $url[, null|string|\Stringable $base = null, array $options = []])`

The `$options` argument accepts an array with a key `logger` whose value is an object implementing `\Psr\Log\LoggerInterface`. See [Logging](#logging) for more information.

#### URL constructor throws

[](#url-constructor-throws)

- `\Rowbot\URL\Exception\TypeError`
    - When the URL parser determines that the given input is not a valid URL.

```
use Rowbot\URL\URL;

// Construct a new URL object.
$url = new URL('https://example.com/');

// Construct a new URL object using a relative URL, by also providing the constructor with the base URL.
$url = new URL('path/to/file.php?query=string', 'http://example.com');
echo $url->href; // Outputs: "http://example.com/path/to/file.php?query=string"

// You can also pass an existing URL object to either the $url or $base arguments.
$url = new URL('https://example.org:123');
$url1 = new URL('foo/bar/', $url);
echo $url1->href; // Outputs: "https://example.org:123/foo/bar/"

// Catch the error when URL parsing fails.
try {
    $url = new URL('http://2001::1]');
} catch (\Rowbot\URL\Exception\TypeError $e) {
    echo 'Invalid URL';
}
```

### URL Members

[](#url-members)

Note: As a convience, both the `__get()` and `__set()` methods will throw an `\InvalidArgumentException` if you try to get or set an invalid property.

#### `string URL::href`

[](#string-urlhref)

The `href` getter returns the serialization of the URL. The `href` setter will parse the entire string updating all the components of the URL with the new values. Providing an invalid URL will cause the setter to throw a `\Rowbot\URL\TypeError`.

#### `readonly string URL::origin`

[](#readonly-string-urlorigin)

The `origin` member is readonly. Its output is in the form of `scheme://host:port`. If a URL does not have a port, then that will be excluded from the output.

#### `string URL::protocol`

[](#string-urlprotocol)

The `protocol` getter, also known as a scheme, returns the protocol of the URL, such as http, ftp, or ssh. The `protocol` setter is used to change the URLs protocol.

#### `string URL::username`

[](#string-urlusername)

The `username` getter returns the username portion of the URL, or an empty string if the URL does not contain a username. The `username` setter changes the URLs username.

#### `string URL::password`

[](#string-urlpassword)

The `password` getter returns the password portion of the URL, or an empty string if the URL does not contain a password. The `password` setter changes the URLs password.

#### `string URL::host`

[](#string-urlhost)

The `host` getter returns the combination of `hostname` and `port`. The output would look like `hostname:port`. If the URL does not have a port, then the port is not present in the output. The `host` setter allows you to change both the `hostname` and `port` at the same time.

#### `string URL::hostname`

[](#string-urlhostname)

The `hostname` getter returns the hostname of the URL. For example, the hostname of `https://example.com:31` would be `example.com`. The `hostname` setter will change the hostname portion of the URL.

#### `string URL::port`

[](#string-urlport)

The `port` getter returns an integer as a string representing the URLs port. If the URL does not have a port, the empty string will be returned instead. The `port` setter updates the URLs port.

#### `string URL::pathname`

[](#string-urlpathname)

The `pathname` getter returns the URLs path. The `pathname` setter updates the URLs path.

#### `string URL::search`

[](#string-urlsearch)

The `search` getter returns the URLs query string. The `search` setter updates the URLs URLSearchParams list.

#### `readonly URLSearchParams URL::searchParams`

[](#readonly-urlsearchparams-urlsearchparams)

Returns the URLSearchParams object associated with this URL allowing you to modify the query parameters without having to clobber the entire query string. This will always return the same object.

#### `string URL::hash`

[](#string-urlhash)

The `hash` getter, also known as a URLs fragment, returns the portion of the URL that follows the "#" character. The `hash` setter updates the portion of the URL that follows the "#".

#### `bool URL::canParse(string|\Stringable $url[, null|string|\Stringable $base = null])`

[](#bool-urlcanparsestringstringable-url-nullstringstringable-base--null)

A static method that allows the user to quickly check if a URL is parsable, without needing to construct a new URL object and wrapping it with a try/catch statement.

#### `?\Rowbot\URL\URL URL::parse(string|\Stringable $url, null|string|\Stringable $base = null)`

[](#rowboturlurl-urlparsestringstringable-url-nullstringstringable-base--null)

A static method that allows the user to parse a string in a way that does not throw exceptions like with the constructor object.

#### `string URL::toJSON()`

[](#string-urltojson)

Returns a JSON encoded string of the URL. Note that this method escapes forward slashes, which is not the default for PHPs `json_encode()`, but matches the default behavior of JavaScripts `JSON.stringify()`. If you wish to control the serialization, then pass the URL obect to the `json_encode()` function.

#### `string URL::jsonSerialize()`

[](#string-urljsonserialize)

The URL object implements the `JsonSerializable` interface allowing you to pass the object as a whole to the json\_encode() function.

#### `string URL::toString()`

[](#string-urltostring)

Returns the serialization of the URL.

#### `string URL::__toString()`

[](#string-url__tostring)

See [URL::toString()](#string-urltostring)

URLSearchParams
---------------

[](#urlsearchparams)

The URLSearchParams object allows you to work with query strings when you don't need a full URL. The URLSearchParams object implements the `Iterator` interface so that you may iterate over the list of search parameters. The iterator will return an array containing exactly 2 items. The first item is the parameter name and the second item is the parameter value.

### The URLSearchParams constructor

[](#the-urlsearchparams-constructor)

`URLSearchParams([iterable|object|string|\Stringable $init])`

#### URLSearchParams constructor throws

[](#urlsearchparams-constructor-throws)

- `\Rowbot\URL\Exception\TypeError`
    - When an iterable is passed and one if its values is not iterable.
    - When an iterable is passed and one of its values is not countable, such as an object that implements `\Iterator`, but not `\Countable`.
    - When an iterable is passed and one of its sequences does not contain exactly 2 items, such as an array that contains only 1 string.

```
use Rowbot\URL\URLSearchParams;

// Construct an empty list of search params.
$params = new URLSearchParams();

// Construct a new list from a query string. Remember that a leading "?" will be stripped.
$params = new URLSearchParams('?foo=bar');

// Construct a new list using an array of arrays containing strings. Alternatively, you could pass an
// object that implements the Traversable interface and whose iterator returns an array of arrays,
// with each array containing exactly 2 items.
$params = new URLSearchParams([
    ['foo', 'bar'],
    ['foo', 'bar'] // Duplicates are allowed!
    ['one', 'two']
]);

// Iterate over a URLSearchParams object.
foreach ($params as $index => $param) {
    if ($index > 0) {
        echo '&';
    }

    echo $param[0] . '=' . $param[1];
}

// Above loop prints "foo=bar&foo=bar&one=two".

// Construct a new list using an object
$obj = new \stdClass();
$obj->foo = 'bar';
$params = new URLSearchParams($obj);

// Copy an existing URLSearchParams object into a new one.
$params1 = new URLSearchParams($params);
```

### URLSearchParams Members

[](#urlsearchparams-members)

#### `void URLSearchParams::append(string $name, string $value)`

[](#void-urlsearchparamsappendstring-name-string-value)

Appends a new name-value pair to the list.

#### `void URLSearchParams::delete(string $name[, string $value])`

[](#void-urlsearchparamsdeletestring-name-string-value)

Deletes all name-value pairs whose name is `$name` from the list. If the optional `$value` is provided, then only pairs with the same name and value are removed.

#### `string|null URLSearchParams::get(string $name)`

[](#stringnull-urlsearchparamsgetstring-name)

Returns the value of the first name-value pair whose name is `$name` in the list or null if there are no name-value pairs whose name is `$name` in the list.

#### `string[] URLSearchParams::getAll(string $name)`

[](#string-urlsearchparamsgetallstring-name)

Returns a list of values of all name-value pairs whose name is `$name`, in list order, or the empty list if there are no name-value pairs whose name is `$name` in the list.

#### `bool URLSearchParams::has(string $name[, string $value])`

[](#bool-urlsearchparamshasstring-name-string-value)

Returns true if there is a name-value pair in the list, and false otherwise.

#### `void URLSearchParams::set(string $name, string $value)`

[](#void-urlsearchparamssetstring-name-string-value)

If the list contains name-value pairs whose name is `$name`, the first name-value pair in the list whose name is `$name` will have its value changed to `$value` and all others following it in the list will be removed. If the list does not contain a name-value pair whose name is `$name` then the new name-value pair will be appended to the list.

#### `void URLSearchParams::sort()`

[](#void-urlsearchparamssort)

Sorts the list of search params by comparing code units. The relative order of name-value pairs with the same name are preserved.

#### `string URLSearchParams::toString()`

[](#string-urlsearchparamstostring)

Returns the serialization of the list of name-value pairs.

### `int URLSearchParams::$size`

[](#int-urlsearchparamssize)

Returns the number of query parameters in the list.

#### `string URLSearchParams::__toString()`

[](#string-urlsearchparams__tostring)

See [URLSearchParams::toString()](#string-urlsearchparamstostring)

Logging
-------

[](#logging)

The given logger logs validation errors. Entries with a level of `warning` are fatal errors that cause the parser to fail. Entries with a level of `notice` are not fatal. All validation errors have an `input` key and either a `column`or `column_range` offset key. Column offsets start at 1.

### Logging context

[](#logging-context)

KeyTypeDescription`input``string`The input string that the parser is operating on at the time of error.`column``positive-int`The column offset of the error.`column_range``array{0: positive-int, 1: positive-int}`Index 0 is the starting column offset, and index 1 is the end column offset. The range is inclusive.`idn_errors``list`A list of strings that represent IDN error constant names.`unicode_domain``string`The domain name as a Unicode string.

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance61

Regular maintenance activity

Popularity43

Moderate usage in the ecosystem

Community16

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 99.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~131 days

Recently: every ~336 days

Total

22

Last Release

242d ago

Major Versions

1.1.1 → 2.0.02018-12-08

2.0.3 → 3.0.02020-02-10

3.1.7 → 4.0.02024-06-21

PHP version history (3 changes)1.0.0PHP &gt;=5.6

2.0.0PHP &gt;=7.1

4.0.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/534ea3958dd4732b3d4d4eee1fe459f93695be1bc28391e704be542592c96a89?d=identicon)[Rowbot](/maintainers/Rowbot)

---

Top Contributors

[![TRowbotham](https://avatars.githubusercontent.com/u/4984601?v=4)](https://github.com/TRowbotham "TRowbotham (641 commits)")[![nyamsprod](https://avatars.githubusercontent.com/u/51073?v=4)](https://github.com/nyamsprod "nyamsprod (2 commits)")

---

Tags

phpquery-stringquerystringuriurlurl-parserurl-parsingurluriquerystringquery-stringWHATWGurl-parserurl-parsing

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/rowbot-url/health.svg)

```
[![Health](https://phpackages.com/badges/rowbot-url/health.svg)](https://phpackages.com/packages/rowbot-url)
```

###  Alternatives

[league/uri

URI manipulation library

1.1k206.4M277](/packages/league-uri)[league/uri-interfaces

Common tools for parsing and resolving RFC3987/RFC3986 URI

536204.9M23](/packages/league-uri-interfaces)[league/uri-components

URI components manipulation library

31932.3M67](/packages/league-uri-components)[sabre/uri

Functions for making sense out of URIs.

29335.2M40](/packages/sabre-uri)[cybercog/laravel-optimus

An Optimus bridge for Laravel. Id obfuscation based on Knuth's multiplicative hashing method.

192564.1k](/packages/cybercog-laravel-optimus)[opis/uri

Build, parse and validate URIs and URI-templates

1920.8M6](/packages/opis-uri)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
