Knowing how to extract the domain name from the URL is one of those skills that every PHP developer needs to have in their arsenal. It can come in handy when you want to perform various operations, such as validating user inputs, parsing data, or building custom web applications.
In this tutorial, I’ll show you the steps to extract the domain name from a URL using PHP. And I’ll try to explain it in a clear and concise manner, so you don’t need to be an expert in PHP to follow along. So, let’s get started and get to the bottom of this together!
Getting the Domain Name
To get the domain name, you can echo the HTTP_HOST
or SERVER_NAME
data elements within the $_SERVER
array. The $_SERVER array is created by the web server, and it contains information such as HTTP headers, URL paths, and script locations.
Here’s how to get the domain name with HTTP_HOST
:
// Echo domain name with HTTP_HOST
echo $_SERVER['HTTP_HOST'];
And now with SERVER_NAME
:
// Echo domain name with SERVER_NAME
echo $_SERVER['SERVER_NAME']
Keep in mind that neither of these solutions are particularly safe, as they prone to spoofing and should not be relied on. The best solution is to store the domain name in a constant yourself, then reference its value as needed throughout your web application’s source code.
How to Choose
Both HTTP_HOST
and SERVER_NAME
can be used to get the domain name of the current URL, but they have slightly different behaviors, and which one to use depends on your specific use case.
HTTP_HOST
is most developers’ go-to way of getting the current URL’s domain name. It gives you the domain name as sent by the client in the HTTP request headers, which can be useful in situations where your website has multiple domain names (or subdomain names) pointing to the same server.
SERVER_NAME
, on the other hand, gives you the server name that is used to identify the server on the network. It’s useful in situations where you want to get the domain name of the current URL, but you want to the most obvious security issues that may arise from using HTTP_HOST
. However, you need to make sure your server’s configured properly to make SERVER_NAME
a reliable option.