Sentry Answers>PHP>

How do I get the full URL in PHP?

How do I get the full URL in PHP?

Nadia S.

The ProblemJump To Solution

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:

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

Example output:

Click to Copy
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:

Click to Copy
/php-folder/php-tests/index.php

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

Click to Copy
/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.

  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Loved by over 4 million developers and more than 100,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.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.