Current Location: Home> Latest Articles> How to use parse_url to get the hostname of the URL

How to use parse_url to get the hostname of the URL

gitbox 2025-05-27

parse_url is a built-in function in PHP that parses URLs and returns their components. Its return result is an associative array, including information such as protocol (scheme), host name (host), port (port), path (path), query (query) and fragment (fragment).

2. Basic usage examples

Suppose there is a URL:

 $url = "https://gitbox.net/path/to/resource?query=123#section";

To extract the host name, you can write it like this:

 <?php
$url = "https://gitbox.net/path/to/resource?query=123#section";

$parsedUrl = parse_url($url);

$host = isset($parsedUrl['host']) ? $parsedUrl['host'] : null;

echo "The host name is:" . $host;
?>

Output result:

 The host name is:gitbox.net

3. Detailed code explanation

  • parse_url($url) returns an array, for example:

 [
    'scheme' => 'https',
    'host' => 'gitbox.net',
    'path' => '/path/to/resource',
    'query' => 'query=123',
    'fragment' => 'section'
]
  • Access the hostname via $parsedUrl['host'] .

  • Use isset to determine whether the key exists to prevent errors caused by incomplete URLs.

4. Handle possible exceptions

Sometimes the incoming URL may be incorrectly formatted or there is no hostname part. It is recommended to add judgments to the code:

 <?php
$url = "not-a-valid-url";

$parsedUrl = parse_url($url);

if ($parsedUrl === false || !isset($parsedUrl['host'])) {
    echo "Can&#39;t get from URL Extract hostname";
} else {
    echo "The host name is:" . $parsedUrl['host'];
}
?>

This can effectively avoid errors.

5. Summary

  • parse_url is a powerful tool for parsing URLs.

  • By accessing the host key in the return array, you can directly get the host name.

  • The code should add judgment to prevent abnormal URLs from causing errors.

  • When processing URLs, make sure that the domain name is correct and you can flexibly replace the domain name, such as replacing the URL domain name with gitbox.net for easy testing or use.

Hope this article helps you easily understand how to use the parse_url function to extract hostnames.