Home >Backend Development >PHP Tutorial >How do I Get the Current Page URL in PHP?

How do I Get the Current Page URL in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 02:52:02646browse

How do I Get the Current Page URL in PHP?

Retrieving the Current Page URL in PHP

In PHP, obtaining the URL of the current page is a straightforward task. This is particularly useful when implementing URL-dependent logic or generating dynamic content.

Solution using $_SERVER['REQUEST_URI']

The most direct method to access the current page URL is through the $_SERVER['REQUEST_URI'] variable. This variable contains the complete URL, including the protocol, domain, and path, but excluding the query string.

Example:

<code class="php"><?php
    echo $_SERVER['REQUEST_URI']; // Example output: /my-page.php
?></code>

Retrieving the Query String

If you need to obtain the query string (the portion of the URL after the "?" symbol), you can utilize the $_SERVER['QUERY_STRING'] variable.

Example:

<code class="php"><?php
    echo $_SERVER['QUERY_STRING']; // Example output: name=John&age=32
?></code>

Additional Notes

  • $_SERVER['REQUEST_URI'] is a heavily utilized variable, and its contents may be modified by external factors such as URL rewriting or proxy servers.
  • PHP also provides other variables related to the current URL, such as $_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT'], and $_SERVER['HTTPS'].

The above is the detailed content of How do I Get the Current Page URL in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn