PHP code example of codeinc / url

1. Go to this page and download the library: Download codeinc/url library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

codeinc / url example snippets


use CodeInc\Url\Url;

$url = Url::fromString('https://www.example.com/search?q=php&page=1#results');

$url->getScheme();       // 'https'
$url->getHost();         // 'www.example.com'
$url->getPath();         // '/search'
$url->getQuery();        // 'q=php&page=1'
$url->getQueryAsArray(); // ['q' => 'php', 'page' => '1']
$url->getFragment();     // 'results'

$url = (new Url())
    ->withScheme('https')
    ->withHost('api.example.com')
    ->withPath('/v2/users')
    ->withQueryParams(['page' => '1', 'limit' => '50']);

echo $url; // https://api.example.com/v2/users?page=1&limit=50

$url = Url::fromString('https://example.com/path?a=1&b=2#frag');

$modified = $url
    ->withScheme('http')
    ->withQueryParams(['c' => '3'])
    ->withoutFragment();

echo $modified; // http://example.com/path?a=1&b=2&c=3
echo $url;      // https://example.com/path?a=1&b=2#frag (unchanged)

$url->withoutScheme();
$url->withoutHost();
$url->withoutPort();
$url->withoutUserInfo();
$url->withoutPath();
$url->withoutFragment();
$url->withoutQuery();            // removes entire query string
$url->withoutQuery(['a', 'b']); // removes specific parameters

// From a PSR-7 UriInterface
$url = Url::fromPsr7Uri($psr7Uri);

// From a PSR-7 ServerRequestInterface
$url = Url::fromPsr7Request($serverRequest);

// Use anywhere a UriInterface is expected
function processUri(UriInterface $uri): void { /* ... */ }
processUri($url);

$url = Url::fromGlobals();