Current Location: Home> Latest Articles> Practical PHP Guide: Easily Retrieve Current Domain, Host, URL, Port, and Request Parameters

Practical PHP Guide: Easily Retrieve Current Domain, Host, URL, Port, and Request Parameters

gitbox 2025-08-10

Get Current Domain

In PHP, you can use the $_SERVER['HTTP_HOST'] variable to get the current domain, which returns the host part of the URL shown in the browser's address bar.

// Get current domain
$domain = $_SERVER['HTTP_HOST'];
echo "Current domain is: " . $domain;

Get Host Name

The host usually refers to the server's name or IP address. You can get the host name of the current server using $_SERVER['SERVER_NAME'].

// Get host name
$host = $_SERVER['SERVER_NAME'];
echo "Current host is: " . $host;

Get Full URL

The full URL includes the protocol, domain, request path, and parameters. You can combine $_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI'] to get the complete URL of the current page.

// Get URL
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo "Current URL is: " . $url;

Get Access Port

The port the server listens on can be obtained through $_SERVER['SERVER_PORT'], showing the port used by the current request.

// Get port
$port = $_SERVER['SERVER_PORT'];
echo "Current port is: " . $port;

Get URL Parameters

The parameters after the question mark in the URL can be accessed using the $_GET array, commonly used to pass data to the server.

// Get parameters
if (isset($_GET['name'])) {
    $name = $_GET['name'];
    echo "The parameter 'name' is: " . $name;
}

Get Complete Website Address

The website address includes the protocol, domain, port, and request path. By checking if the protocol is HTTPS and combining the host and URI, you can build the full URL.

// Get website address
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$path = $_SERVER['REQUEST_URI'];
$url = $protocol . $host . $path;
echo "Current website address is: " . $url;

Get Request Path

The request path refers to the part of the URL after the domain (including parameters), which can be directly obtained via $_SERVER['REQUEST_URI'].

// Get path
$path = $_SERVER['REQUEST_URI'];
echo "Current path is: " . $path;

Get Proxy IP

The proxy server's IP address can be accessed through $_SERVER['HTTP_X_FORWARDED_FOR'], but note this information may be forged and should only be used as a reference.

// Get proxy
$proxy = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
echo "Current proxy is: " . $proxy;

Summary

The methods above cover common ways to retrieve environment information of the current access in PHP, which helps developers handle requests, generate dynamic links, or perform data analysis. These variables are provided by PHP's built-in $_SERVER superglobal array and allow quick access to various details of client requests.