Get domain name in PHP

php
tutorial
domain
url
Nabil Hassen
Nabil Hassen
Nov 26, 2025
How to get domain names from URLs, emails or current page
Last updated on Nov 26, 2025
Table of contents:

Extract domain in PHP: From URL, Email or Current Page

In backend PHP development, extracting domain names is often required for tasks such as building canonical URLs, parsing user-supplied links or emails, routing, logging, or validation. In this article, we cover how to obtain domain names in PHP in several real-world contexts: from the current request, from a URL string, or from an email address. We also cover how to handle scheme (http/https) and optionally remove subdomains to get the “base” or registrable domain.

Getting the current page’s domain

To retrieve the domain used in the current request, the site address where your PHP code is running, you can rely on PHP’s $_SERVER superglobal variables:

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'];
$domain = $scheme . '://' . $host;
echo $domain;

Explanation:

  • $_SERVER['HTTP_HOST'] gives the host header sent by the client (could include port).
  • As a fallback, $_SERVER['SERVER_NAME'] can be used if HTTP_HOST is not set.
  • We detect the scheme (HTTPS or HTTP) to build a full URL including protocol.

This approach yields the exact domain (and optionally port) the user used to request the page. It’s commonly used for generating canonical URLs or redirects.

Security note: Because HTTP_HOST is derived from a client-supplied header, it can be spoofed. For security-sensitive tasks (authentication, token generation, access control), avoid trusting HTTP_HOST. Use a fixed configuration value or server-controlled name instead.

Extracting domain from a URL string

When you have a URL (from user input, configuration, referral data, etc.) and you want to extract its domain, PHP’s built-in parse_url() is the standard tool:

$url = 'https://www.example.com/path/page.php?foo=bar';
$host = parse_url($url, PHP_URL_HOST);
echo $host; // e.g. "www.example.com"

parse_url() parses a URL into components (scheme, host, path, query, fragment, etc.). Using the PHP_URL_HOST option returns the host (domain) component as a string.

This works reliably when the input is a full, valid URL.

Limitations and caveats:

  • If the URL lacks a scheme (e.g. "example.com/path"), parse_url() may misinterpret the string as a relative path and fail to extract a host.
  • If the URL is malformed or not properly encoded, parsing may produce unexpected results or return null.

Hence, when dealing with user-supplied or external input, it is wise to first validate or normalize the URL (for example by ensuring it has a scheme) before calling parse_url().

Get domain without subdomain

By default, parse_url() returns the full host including any subdomains. For example, from https://sub.www.example.co.uk, you’ll get sub.www.example.co.uk. Often you want only the “base” or “registrable” domain (e.g. example.co.uk).

A naive way to strip subdomains might look like this:

$host = parse_url($url, PHP_URL_HOST);
$host = preg_replace('/^www\./i', '', $host);

This handles the common case of a “www.” prefix. However, this approach fails when:

  • The subdomain is not “www” (e.g. api.example.com, blog.example.co.uk).
  • The domain has a multi-part TLD (e.g. .co.uk, .org.au), where simply taking the last two labels may be incorrect.
  • There are deeper subdomains (e.g. a.b.c.example.com).

Because of these issues, reliably extracting the base domain from arbitrary hosts is nontrivial. A fully correct solution needs awareness of the public suffix list (all valid TLDs and multi-part TLDs). Without that, any regex or heuristic-based method will be brittle.

If precise domain extraction is critical in your application, use a well-maintained, public-suffix aware library. If not, the heuristic approach may suffice but be aware of its limitations.

Extracting domain from an email address

Email addresses have a simple structure: local-part@domain. To get the domain part in PHP:

$email = '[email protected]';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$domain = explode('@', $email)[1];
echo $domain; // "example.com"
} else {
// invalid email
}

Alternatively:

$domain = substr(strstr($email, '@'), 1);

Important points:

  • Validate the email format first using filter_var(..., FILTER_VALIDATE_EMAIL) before extraction.
  • This method returns exactly what is after the @. If the email is nonstandard (contains multiple @, or extra data), further validation or sanitization may be required.

This method is straightforward and works well when you trust or validate email input.

Caveats, edge cases, and best practices

  • Subdomain stripping is error-prone. Regex or naive splitting on “.” may fail for multi-level TLDs or complex hosts. Use a public-suffix aware approach when accuracy matters.
  • Server-provided host data (especially HTTP_HOST) comes from client headers, avoid trusting it for security-critical code.
  • Always validate and sanitize external input (URLs and emails) before parsing. For instance, ensure a URL has a scheme and is well-formed before using parse_url().
  • Be aware of internationalized domain names (IDN). Plain string or regex operations may not handle non-ASCII domain names; IDN/Punycode handling may be needed depending on use case.

Conclusion

PHP provides effective, built-in tools to extract domain names in typical web use cases:

  • Use $_SERVER['HTTP_HOST'] (with scheme detection) for the current request domain.
  • Use parse_url() to parse a URL string and extract the host.
  • Use simple string manipulation or explode('@') to extract domain from an email address.
  • For extracting a registrable domain (without subdomains), rely on a public-suffix aware library rather than naive string hacks.

While simple cases are easy, edge cases (subdomains, multi-level TLDs, malformed input) require careful handling. For robust, production-ready code, validate inputs and prefer library-based parsing when domain correctness matters.

Nabil Hassen
Nabil Hassen
Full Stack Web Developer

Stay Updated.

I'll you email you as soon as new, fresh content is published.

Thanks for subscribing to my blog.

Latest Posts