Tags
Asked 2 years ago
10 Aug 2021
Views 221
Fleta

Fleta posted

How get localhost URL in PHP ?

How get localhost URL in PHP ?
Rasi

Rasi
answered Jun 24 '23 00:00

In PHP, you can get the localhost URL using the $_SERVER superglobal variable . The $_SERVER['HTTP_HOST'] provides the hostname part of the URL, and $_SERVER['SERVER_PORT'] gives the port number if it is different from the default (80 for HTTP or 443 for HTTPS).

Here's an example of how you can construct the localhost URL dynamically in PHP:


$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$port = $_SERVER['SERVER_PORT'];

$localhostURL = $protocol . '://' . $host;
if (($protocol === 'http' && $port != 80) || ($protocol === 'https' && $port != 443)) {
    $localhostURL .= ':' . $port;
}

echo $localhostURL;

Post Answer