Search by

himelali / urlkit

himelali

A modern, powerful and framework-independent PHP URL management toolkit with Static and Fluent APIs.

v1.0.0 2026-11-22 15:41 UTC

This package is auto-updated.

Last update: 2026-11-22 15:46:35 UTC


README

CI Latest version PHP version License

A modern, powerful and framework-independent PHP URL management toolkit with Static and Fluent APIs.

use Himelali\URLKit\UrlKit;
use Himelali\URLKit\UrlKitBuilder;

UrlKit::normalize('HTTPS://Example.COM:443/products?id=10'); // => 'https://example.com/products?id=10'

UrlKitBuilder::make('https://example.com/products?page=1&sort=latest')
    ->withHost('shop.example.com')
    ->setQuery('page', 2)
    ->withoutQuery(['sort'])
    ->toString(); // => 'https://shop.example.com/products?page=2'

Himelali URLKit parses URLs strictly (RFC 3986), never repairs malformed input silently, keeps every value object immutable, and treats security as a first-class concern: SSRF and open-redirect protection, safe link sanitization and tamper-proof signed URLs.

Contents

Features

  • Two consistent APIs. A static UrlKit class and an immutable, fluent UrlKitBuilder. Both use the same services, so they always agree.
  • Strict, lossless parsing. RFC 3986 with IPv4/IPv6, credentials, Unicode (IRI) and internationalized domains. Parsed URLs round-trip exactly.
  • Query management with WHATWG semantics (addQuery appends, setQuery replaces), repeated keys, and nested PHP-style parameters, without parse_str() key mangling.
  • Path management. Segments, file names, dot-segment removal and slash control.
  • Domains. Hostname, registrable domain, subdomain and public suffix from the bundled Public Suffix List; punycode conversion; IP classification.
  • Two-tier normalization. A safe normalize() and an SEO-oriented canonicalize(). Neither sorts the query unless asked.
  • Comparison. Exact equals() vs normalized equivalent(), wildcard matches() and diff().
  • Security. Default-deny policies, SSRF checks with DNS pinning, open-redirect protection, link sanitization and HMAC-SHA256 signed and expiring URLs.
  • Extras. RFC 6570 URI templates, slugs, UTM and hreflang helpers, asset and CDN URLs, mailto:/tel:/deep links, URL extraction from text and immutable collections.
  • Integrations. Plain PHP, Laravel (auto-discovered) and Symfony, plus optional, SSRF-safe network diagnostics.
  • No required runtime dependencies.

Requirements

  • PHP 8.2 or newer
  • Optional: ext-intl for internationalized domain names and transliterated slugs; ext-mbstring for Unicode lowercasing in sanitize(); ext-curl or guzzlehttp/guzzle for the network diagnostics

Without ext-intl, Unicode host conversions throw a clear URLException instead of returning a wrong result. ASCII and punycode hosts work fully.

Installation

composer require himelali/urlkit

See installation for framework setup and configuration.

Quick start

The examples in this README and in docs/ are executed by the test suite. They assume the application root https://example.com and a current request for https://example.com/products?page=2 (see quick start).

UrlKit::current();                       // => 'https://example.com/products'
UrlKit::to('/cart', ['ref' => 'nav']);   // => 'https://example.com/cart?ref=nav'
UrlKit::host('https://shop.example.co.uk/a'); // => 'shop.example.co.uk'
UrlKit::domain('https://shop.example.co.uk/a'); // => 'example.co.uk'
UrlKit::getQuery('https://example.com/products?page=2', 'page'); // => '2'
UrlKit::addQuery('https://example.com/products', ['page' => 2, 'sort' => 'latest']); // => 'https://example.com/products?page=2&sort=latest'

Static API

Every operation is a static method that takes a URL and returns a new URL string (or a value).

UrlKit::withPath('https://example.com/a?x=1', '/my docs');  // => 'https://example.com/my%20docs?x=1'
UrlKit::removeQuery('https://example.com/?a=1&b=2', 'a');   // => 'https://example.com/?b=2'
UrlKit::segments('https://example.com/blog/2026/hello');    // => ['blog', '2026', 'hello']
UrlKit::isValid('https://example.com');                     // => true
UrlKit::isValid('example.com');                             // => false

Full reference: static API.

Fluent API

UrlKitBuilder is immutable: every method returns a new instance.

$original = UrlKitBuilder::make('https://example.com?page=1');
$modified = $original->setQuery('page', 2);

$original->toString(); // => 'https://example.com?page=1'
$modified->toString(); // => 'https://example.com?page=2'

Full reference: fluent API.

Query management

$url = 'https://example.com/search?q=php&tags[]=url&tags[]=kit';

UrlKit::getQueries($url);               // => ['q' => 'php', 'tags' => ['url', 'kit']]
UrlKit::addQuery($url, 'q', 'laravel'); // => 'https://example.com/search?q=php&tags[]=url&tags[]=kit&q=laravel'
UrlKit::setQuery($url, 'q', 'laravel'); // => 'https://example.com/search?q=laravel&tags[]=url&tags[]=kit'
UrlKit::removeQuery($url, 'tags');      // => 'https://example.com/search?q=php'

More: query management.

Path management

UrlKit::appendPath('https://example.com/api', 'users', '42'); // => 'https://example.com/api/users/42'
UrlKit::replacePath('https://example.com/api/v1/users', 'v1', 'v2'); // => 'https://example.com/api/v2/users'
UrlKit::extension('https://example.com/files/report.PDF');   // => 'PDF'

More: path management.

Domain management

UrlKit::extractSubdomain('https://shop.eu.example.co.uk');  // => 'shop.eu'
UrlKit::extractPublicSuffix('https://shop.eu.example.co.uk'); // => 'co.uk'
UrlKit::toPunycode('bücher.de');                            // => 'xn--bcher-kva.de'
UrlKit::isPrivateIPAddress('http://192.168.1.10/');         // => true

More: domain management.

Normalization

UrlKit::normalize('HTTPS://Example.COM:443/a/./b/../c?b=2&a=1');    // => 'https://example.com/a/c?b=2&a=1'
UrlKit::canonicalize('https://example.com/a?utm_source=x&id=1#top'); // => 'https://example.com/a?id=1'

More: normalization.

Encoding

UrlKit::encodePath('/my files/report.pdf'); // => '/my%20files/report.pdf'
UrlKit::encodePath('/already%20encoded');   // => '/already%20encoded'
UrlKit::rawEncode('a b&c');                 // => 'a%20b%26c'

More: encoding.

Validation

Syntax validation is not security validation:

UrlKit::isValid('javascript:alert(1)');    // => true
UrlKit::isSafeURL('javascript:alert(1)');  // => false

More: validation.

Security

UrlKit::isSafeURL('http://169.254.169.254/latest/meta-data/'); // => false
UrlKit::isSafeRedirect('//evil.com');                          // => false
UrlKit::safeRedirect('https://evil.com/phish', '/dashboard');  // => '/dashboard'
UrlKit::sanitizeURL("java\tscript:alert(1)", '#');             // => '#'

URLKit separates syntax checks, policy checks and (explicit) DNS checks, and documents what validation cannot guarantee. Read security before using URLs that your server fetches.

Signed URLs

$link = UrlKit::temporary('https://example.com/download/report.pdf', 3600);

UrlKit::verifySignature($link);                                  // => true
UrlKit::verifySignature(str_replace('report', 'secret', $link)); // => false

Configure a signing key of at least 32 bytes; see security.

Templates

UrlKit::expand('https://api.example.com/users/{id}{?page,sort}', ['id' => 42, 'page' => 2]); // => 'https://api.example.com/users/42?page=2'
UrlKit::interpolate('/users/:id/posts/:slug', ['id' => 42, 'slug' => 'hello']);              // => '/users/42/posts/hello'

More: templates.

Collections

$urls = UrlKit::extract('Docs at https://example.com/docs, blog at https://blog.example.org.');

$urls->toArray();  // => ['https://example.com/docs', 'https://blog.example.org']
$urls->domains();  // => ['example.com', 'example.org']

More: collections, examples and helpers (slugs, SEO, assets, protocol links).

Laravel

Install the package; the service provider and a global UrlKit alias are auto-discovered. The class is named UrlKit so it never clashes with Laravel's own URL facade: both can be used in the same file. See Laravel.

Symfony

Wire SymfonyURLResolver to the request stack. See Symfony.

Exceptions

Every exception extends Himelali\URLKit\Exceptions\URLException:

UrlKit::parseOrFail('https://exa mple.com'); // throws InvalidURLException
UrlKit::parse('https://exa mple.com');       // => null

More: exceptions.

Testing

composer test           # PHPUnit
composer analyse        # PHPStan, level max
composer format:check   # PHP-CS-Fixer
composer lint           # PSR-12 (PHP_CodeSniffer)
composer check          # all of the above

The suite includes RFC 3986 and RFC 6570 example tables, property-based tests, security payload tests, framework integration tests, and tests that execute every example in the documentation. CI runs it on PHP 8.2 to 8.5, with the lowest and highest allowed dependencies, without ext-intl, on Windows, against Symfony 6.4 LTS, and with a 95% line-coverage gate.

Contributing

See CONTRIBUTING.md. Report security issues privately as described in SECURITY.md, not in public issues. Release history: CHANGELOG.md.

License

Himelali URLKit is open-source software licensed under the MIT license.

It bundles a snapshot of the Public Suffix List in resources/, which is subject to the Mozilla Public License 2.0.

Created by Md. Himel Ali.