Open In App

How to get the Current URL in PHP ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP, Getting the current URL is a common requirement for various tasks such as building dynamic navigation menus, tracking user activity, or generating links. PHP provides several superglobal arrays and functions to retrieve different parts of the URL, including the protocol, domain, path, query parameters, etc.

Approach

  • Using $_SERVER[‘REQUEST_URI’]: Retrieves the URI (Uniform Resource Identifier) of the current request.
  • Using $_SERVER[‘HTTP_HOST’]: Retrieves the hostname portion of the current URL.
  • Using $_SERVER[‘QUERY_STRING’]: Retrieves the query string portion of the current URL, if present.

Syntax

// Get the current URL
$currentURL = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $currentURL;

Important Points

  • Ensure proper handling of user input to prevent security vulnerabilities such as XSS (Cross-Site Scripting) attacks.
  • Consider using HTTPS (HTTP Secure) to encrypt data transmitted over the network for enhanced security.

Difference Between $_SERVER[‘REQUEST_URI’] and $_SERVER[‘HTTP_HOST’]

$_SERVER[‘REQUEST_URI’] $_SERVER[‘HTTP_HOST’]
Retrieves the URI of the current request, including the path and query string Retrieves the hostname portion of the current URL
Does not include the protocol or domain Does not include the path or query string

Features

  • Dynamic URL Generation: Use PHP to dynamically generate URLs based on the current request, enabling dynamic content rendering and navigation.
  • Query String Parsing: Retrieve and parse query string parameters from the current URL to extract and process user input or application state.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads