How to get the full URL path in PHP

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.


Will output a full URL in PHP.


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';


A similar array item is populated from the header request. Always check it is defined before using it.

$httpHost = isset($_SERVER['HTTP_HOST']) ?? '';


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.



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.

# Outputs

echo $_SERVER['PHP_SELF'];
# Outputs

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.


Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.

Reject non-essential Accept all