How do I get the full URL in PHP?

Nadia S.
jump to solution

The Problem

You want to get hold of the entire URL as it would appear in the browser’s address bar. How do you do this in PHP?

The Solution

To get the full URL, we add the values of the $_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI'] variables to the https:// protocol:

$requestUrl = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $requestUrl;

Example output:

https://localhost:3000/php-folder/php-tests/index.php

The difference between the $_SERVER['PHP_SELF'] and $_SERVER['REQUEST_URI'] variable

We use $_SERVER['REQUEST_URI'] to build the full URL as it would appear in the browser’s address bar. In many cases, $_SERVER['PHP_SELF'] and $_SERVER['REQUEST_URI'] will return the same file path and filename so they can be used interchangeably, but they differ in the following ways:

The $_SERVER['PHP_SELF'] variable returns the path and filename of the script that is being served. For example:

/php-folder/php-tests/index.php

The $_SERVER['REQUEST_URI'] variable returns the URI that’s used which includes any query parameters. For example:

/php-folder/php-tests/index.php?param=value

The output of $_SERVER['PHP_SELF'] and $_SERVER['REQUEST_URI'] will differ when using the directory of a virtual server, or when the URL is rewritten.

How do I make a redirect in PHP?
Nadia S.
How do I print the call stack in PHP?
Richard C.
Convert a date format in PHP?
Nadia S.

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry