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.
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
)
/pathExample 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"
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
