How to get current page URL in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP $_SERVER Superglobal Variable

You can use the $_SERVER built-in variable to get the current page URL in PHP. The $_SERVER is a superglobal variable, which means it is always available in all scopes.

Also if you want full URL of the page you'll need to check the scheme name (or protocol), whether it is http or https as shown in the example below:

Example

Download
  • <?php
  • $uri = $_SERVER['REQUEST_URI'];
  • echo $uri; // Outputs: URI
  •  
  • $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  •  
  • $url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  • echo $url; // Outputs: Full URL
  •  
  • $query = $_SERVER['QUERY_STRING'];
  • echo $query; // Outputs: Query String
  • ?>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.