PHP parse_url Function: Usage, Parameters, Return Values and Examples

This article explains the PHP parse_url() function, detailing its signature, optional component parameter, return types, and provides two complete code examples with expected output to illustrate how URLs are decomposed into scheme, host, port, user, password, path, query and fragment parts.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP parse_url Function: Usage, Parameters, Return Values and Examples

The parse_url() function parses a URL string and returns its components as an associative array or a single component when the optional $component argument is supplied.

Signature: mixed parse_url(string $url[, int $component = -1]) Parameters: $url – the URL to be parsed; invalid characters are replaced with an underscore. $component – one of the PHP_URL_* constants (e.g., PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY, PHP_URL_FRAGMENT). When PHP_URL_PORT is requested, an integer is returned; otherwise a string is returned.

Return value: If the URL is severely malformed, FALSE may be returned. Without the $component argument, an associative array is returned containing any of the following keys that were present in the URL: scheme, host, port, user, pass, path, query, fragment. When $component is specified, the function returns the corresponding string (or integer for PHP_URL_PORT) or NULL if that part does not exist.

Example 1:

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>

Output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

Example 2:

<?php
$url = '//www.example.com/path?googleguy=googley';
// Before PHP 5.4.7 this would output the path "//www.example.com/path"
var_dump(parse_url($url));
?>

Output:

array(3) {
  ["host"]=> string(15) "www.example.com"
  ["path"]=> string(5) "/path"
  ["query"]=> string(17) "googleguy=googley"
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendURL parsingphp-functionsparse_url
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.