How to get a domain name from a URL using PHP
Working with URLs is a common task in PHP applications. Whether you are analyzing links, filtering user inputs, or extracting website information, you may often need to get only the domain name from a full URL. Thankfully, PHP provides a built-in function that makes this simple: parse_url().
Understanding the parse_url() Function
The parse_url() function takes a URL string and returns an associative array that contains its components, such as:
- scheme — protocol (http, https, ftp, etc.)
- host — domain name
- path — remaining URL path
- port, query, fragment, etc.
Example:
parse_url("https://example.com/about");
This will return an array like:
[
"scheme" => "https",
"host" => "example.com",
"path" => "/about"
]
Get Only the Domain Name
If you only need the hostname (domain), you can access the host key from the returned array.
Example
<?php
$url = "https://devnote.in/laravel";
$domain = parse_url($url);
echo "Your domain is: " . $domain['host'];
Output
Your domain is: devnote.in
This is the simplest and most reliable way to get a domain name from a URL in PHP.
Get Full URL (Protocol + Domain + Path)
If you want the complete URL structure including the protocol and path, you can combine values from parse_url():
<?php
$url = "https://devnote.in/laravel";
$domain = parse_url($url);
echo "Full URL: " . $domain['scheme'] . "://" . $domain['host'] . $domain['path'];
Output
Full URL: https://devnote.in/laravel
This is useful when you want to display clean URLs or rebuild parts of the link.
Final Thoughts
Using parse_url() is the most practical way to extract domain names from URLs in PHP. You don’t need regex or external libraries. Just remember to validate URLs before parsing to avoid unexpected results.