How to get full URL in php

How to get full URL in php

To get the full URL in PHP, you can use a combination of server variables and PHP functions. Here’s an example:

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$uri = $_SERVER['REQUEST_URI'];

$fullURL = $protocol . $host . $uri;

echo $fullURL;

In this example, the $protocol variable checks if the HTTPS server variable is set and equal to 'on'. If true, it sets the protocol to 'https://'; otherwise, it sets it to 'http://'. This handles cases where the script is accessed over a secure HTTPS connection.

The $host variable retrieves the value of the HTTP_HOST server variable, which represents the hostname of the server.

The $uri variable retrieves the value of the REQUEST_URI server variable, which represents the URI or path of the requested resource.

Finally, the $fullURL variable concatenates the $protocol, $host, and $uri variables to form the complete URL.

Please note that the REQUEST_URI server variable includes the query string if present. If you want to exclude the query string from the URL, you can use the SCRIPT_NAME server variable instead.

$fullURL = $protocol . $host . $_SERVER['SCRIPT_NAME'];

By using this code, you will obtain the full URL of the current page being accessed. This is howto get full URL in php.