php
  1. php-get-current-page-url

PHP Get Current Page URL

In this tutorial, you will learn how to get the current page URL in PHP.

Syntax

$current_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

Example

$current_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $current_url;

Output

http://example.com/current-page-url.php

Explanation

The $_SERVER is an array that contains server and environment variables. In this case, we are accessing the following keys:

  • HTTP_HOST: the hostname of the server.
  • REQUEST_URI: the URI which was given in order to access this page.

We concatenate these values with the http:// prefix to create the current page URL.

Use

You can use the current page URL for various purposes such as:

  • Building links to the current page.
  • Storing the current page URL in the database for future reference.
  • Redirecting the user to the current page after form submission.

Important Points

  • The $_SERVER['HTTP_HOST'] variable returns the domain name of the current page.
  • The $_SERVER['REQUEST_URI'] variable returns the path and query string of the current page.
  • Always include the http:// prefix when building the current page URL.

Summary

In this tutorial, you learned how to get the current page URL in PHP using the $_SERVER array. The current page URL can be used for various purposes such as building links, storing in the database, and redirecting the user after form submission.

Published on: