Knowing the URL path in PHP is an essential task when programming, but how do I get the full URL in PHP? Have you always wanted to know how to use PHP to get the URL address? Read more for the solution including an example of free PHP code you can use in your application.
Using PHP Superglobals to get the URL path
PHP has a collection of Superglobals, which are variables in PHP that are always in scope. That means they can be used in any file, multiple times. To get the full URL in PHP we can use $_SERVER
. Stored within the server superglobal array are REQUEST_SCHEME
, HTTP_HOST
, and REQUEST_URI
.
echo $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Will output a full URL in PHP.
https://127.0.0.1/index.php
REQUEST_SCHEME
Isn't listed in the official PHP document because it's sent as a header with the request, which PHP subsequently populates into the server superglobal. Because of this, it may not always be defined. To avoid the common warning: Undefined array key PHP error, you should check if it exists before using it.
$requestScheme = isset($_SERVER['REQUEST_SCHEME']) ?? 'http';
HTTP_HOST
A similar array item is populated from the header request. Always check it is defined before using it.
$httpHost = isset($_SERVER['HTTP_HOST']) ?? '127.0.0.1';
REQUEST_URI
This array item of the server superglobal tells you the URI of the accessed page. Perfect for routing and loading the correct logic based on the page visited.
/my_account.php?user=1
PHP_SELF
Another option to use is PHP self. This array item is similar to the REQUEST_URI
, however, it will not include the query parameters. This is better when you're looking to route back to your server without the query string.
echo $_SERVER['REQUEST_URI'];
# Outputs
/my_account.php?user=1
echo $_SERVER['PHP_SELF'];
# Outputs
/my_account.php
If REQUEST_SCHEME
isn't available to you, it's possible to use the HTTPS
array element. This sets a value if the request was queried using the HTTPS protocol.
echo !empty($_SERVER['HTTPS']) ? 'https' : 'http';
Normally when queried over HTTPS the server array variable may look like the following.
[HTTPS] => on
All server superglobal array items are in uppercase by design. To view the rest of the array items, use print_r to print the array to the screen. The SERVER_NAME
is another similar array item you could use in combination with those above to get the full URL path in PHP.
print_r($_SERVER);