Documentation for crwlr / url (v2.1)

Getting Started

The Swiss Army Knife for Urls

This package is for you when PHP's parse_url() is not enough.

Key Features:

  • Parse a url and access or modify all its components separately.
  • Resolve any relative reference you may find in an HTML document to an absolute url, based on the document's url.
  • Get not only the full host of a url, but also the registrable domain, the domain suffix and the subdomain parts of the host separately (Thanks to the Mozilla Public Suffix List).
  • An advanced API to access and manipulate the URL query component.
  • Compare urls or components of urls (e.g. checking if different urls point to the same host or domain)
  • Thanks to symfony/polyfill-intl-idn it's also no problem to parse internationalized domain names (IDN).
  • Includes an adapter class which implements the PSR-7 UriInterface.

Requirements

Requires PHP version 8.0 or above.

Installation

Install the latest version with:

composer require crwlr/url

Usage

Including the package

<?php

include('vendor/autoload.php');

use Crwlr\Url\Url;

To start using the library include composer's autoload file and import the Url class so you don't have to write the full namespace path again and again. Further code examples skip the above.

Parsing urls

Parsing a url is easy as pie:

$url = Url::parse('https://john:123@www.example.com:8080/foo?bar=baz');

The static parse method of the Url class provides a convenient way to create a new instance and then access all of it's components separately.

// Accessing url components via method calls
$port = $url->port();                   // => 8080
$domainSuffix = $url->domainSuffix();   // => "com"
$path = $url->path();                   // => "/foo"
$fragment = $url->fragment();           // => NULL

Of course, you can also get a new instance using the new keyword.

$url = new Url('https://www.steve.jobs/');

Relative urls

New in v1.0 of this package is, that you can obtain an instance of Url from a relative url as well. Previous versions throw an InvalidUrlException when the url string doesn't contain a valid scheme component.

$url = Url::parse('/some/path?query=string');
var_dump($url->__toString());   // => '/some/path?query=string'
var_dump($url->scheme());       // => null
var_dump($url->path());         // => '/some/path'