get domain from url in php

To get the domain from a URL in PHP, the built-in parse_url() function is the recommended method. 

Using parse_url() (Recommended) 

The parse_url() function can extract various components of a URL string, including the host. 

php

<?php
$url = "https://www.example.com/path/to/page.html?query=value";

// Get only the 'host' component from the URL
$host = parse_url($url, PHP_URL_HOST);

echo $host;
// Output: www.example.com
?>

Note: If the input URL is missing the scheme (http:// or https://), parse_url() might not work as expected. You can add a default scheme if one is not present in the original string. 

Getting the Root Domain (without ‘www’ or subdomains)

If you need only the root domain (e.g., example.com from www.example.com or sub.example.com), you can use string manipulation with str_replace() and explode()

php

<?php
$url = "https://sub.example.com";

// 1. Get the host name
$host = parse_url($url, PHP_URL_HOST);

// 2. Remove 'www.' if it exists
$host = str_replace('www.', '', $host);

// This simple method works for most common domains but may fail with complex TLDs like co.uk.
echo $host;
// Output: example.com
?>

For robust handling of complex top-level domains (like .co.uk.gouv.fr), string manipulation can be unreliable. A professional solution would use a library that incorporates the Public Suffix List, such as the PHP Domain Parser library.




Leave a Reply