PHP provides the parse_url function, which parses a URL and returns an associative array of its components that are present. This function does not validate the URL or follow any standards; it simply breaks the URL into its individual parts.
<?php
$components = parse_url('https://username:psw@example.com:8080/test?param=1#anchor');
echo $components['scheme'].PHP_EOL; // https
echo $components['user'].PHP_EOL; // username
echo $components['pass'].PHP_EOL; // psw
echo $components['host'].PHP_EOL; // example.com
echo $components['port'].PHP_EOL; // 8080
echo $components['path'].PHP_EOL; // /test
echo $components['query'].PHP_EOL; // param=1
echo $components['fragment'].PHP_EOL; // anchor
Since PHP 8.5, we can use a new extension named URI for securely parsing and modifying URIs and URLs according to the RFC 3986 and the WHATWG URL standards via an object-oriented approach. The URI extension provides a new Uri\Rfc3986\Uri class to represent and manipulate URLs and URIs as objects. URI extension is a part of the PHP core and there is no additional installation needed.
<?php
use Uri\Rfc3986\Uri;
$uri = new Uri('https://username:psw@example.com:8080/test?param=1#anchor');
echo $uri->getScheme().PHP_EOL; // https
echo $uri->getUsername().PHP_EOL; // username
echo $uri->getPassword().PHP_EOL; // psw
echo $uri->getHost().PHP_EOL; // example.com
echo $uri->getPort().PHP_EOL; // 8080
echo $uri->getPath().PHP_EOL; // /test
echo $uri->getQuery().PHP_EOL; // param=1
echo $uri->getFragment().PHP_EOL; // anchor
The URI extension not only allows for accurate, and secure parsing of URLs according to the relevant standards, but it also provides a way to modify individual URL components.
<?php
use Uri\Rfc3986\Uri;
$uri = new Uri('https://example.com:8080');
$uri = $uri->withPort(443);
echo $uri->toString(); // https://example.com:443
Leave a Comment
Cancel reply