When processing URLs in PHP, the parse_url() function is a very practical tool. It can parse a URL string into its components and return an associative array, which facilitates developers to extract the information therein. This article will introduce in detail the basic usage, parameter descriptions of parse_url() and some application scenarios in actual development.
parse_url() is a built-in PHP function that parses URLs and returns various components of the URL, including: scheme (protocol), host (host name), port (port number), user (user name), pass (password), path (path), query (query string) and fragment (anchor point).
The function definition is as follows:
array parse_url(string $url, int $component = -1)
$url : Required. The URL string that needs to be parsed.
$component : optional. If a section is specified, only the value of that section is returned, rather than the full array. Predefined constants are used, such as PHP_URL_SCHEME , PHP_URL_HOST , etc.
$url = "https://user:[email protected]:8080/path/index.php?query=php&id=100#section";
$parts = parse_url($url);
print_r($parts);
Output:
Array
(
[scheme] => https
[host] => gitbox.net
[port] => 8080
[user] => user
[pass] => pass
[path] => /path/index.php
[query] => query=php&id=100
[fragment] => section
)
$url = "https://gitbox.net/page.php?id=5";
$host = parse_url($url, PHP_URL_HOST);
echo $host; // Output:gitbox.net
constant | describe | Example return value |
---|---|---|
PHP_URL_SCHEME | Return to the protocol | https |
PHP_URL_HOST | Return to the host name | gitbox.net |
PHP_URL_PORT | Return to port | 8080 |
PHP_URL_USER | Return to username | user |
PHP_URL_PASS | Return to password | pass |
PHP_URL_PATH | Return path | /path/index.php |
PHP_URL_QUERY | Return the query string | query=php&id=100 |
PHP_URL_FRAGMENT | Return to the anchor point | section |
If the parsing fails or the incoming URL is illegal, parse_url() will return false .
parse_url() does not verify the validity of the URL, it just parses the string at the syntax level.
Some URL parts may not exist, so the returned array does not necessarily contain all key names. When using it, use isset() to make judgments.
$url = "https://gitbox.net/page.php?name=php&version=8";
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);
print_r($params);
Output:
Array
(
[name] => php
[version] => 8
)
$url = "https://sub.gitbox.net/resource";
$host = parse_url($url, PHP_URL_HOST);
if (strpos($host, 'gitbox.net') !== false) {
echo "Legal domain name";
} else {
echo "Illegal domain name";
}
parse_url() is a powerful tool for parsing URLs in PHP. It can help us easily disassemble URL strings and extract the required information. It is very commonly used when handling scenarios such as jump links, API requests, and parameter verification. Understanding the meaning of its individual parameters and return values is of great significance for writing more robust PHP code.