How to Get the Previous Url Using PHP

As a PHP developer, you may come across a situation where you need to get the previous URL in your application.

The previous URL refers to the URL of the page that the user came from before landing on the current page.

This information can be useful in various scenarios, such as keeping track of user navigation, redirecting users to the previous page, or displaying a back button.

In this post, we will explain how to get the previous URL in PHP.

We will also provide code examples to demonstrate how to use this information in your application.


Getting the Previous URL

The previous URL can be retrieved from the $_SERVER superglobal array in PHP.

The $_SERVER array contains information about the server and the current request, including the URL of the page that the user came from.

To get the previous URL, you can use the following code:

$previous_url = $_SERVER['HTTP_REFERER'];

The HTTP_REFERER key in the $_SERVER array stores the URL of the page that the user came from.

Note that the HTTP_REFERER key is not always set, as some browsers and security software may block it.

Using the Previous URL

Once you have retrieved the previous URL, you can use it in various ways in your application.

Here are a few examples:

Redirecting the User to the Previous Page

If the user needs to be redirected to the previous page, you can use the following code:

$previous_url = $_SERVER['HTTP_REFERER'];
header('Location: ' . $previous_url);

This code retrieves the previous URL and then uses the header function to redirect the user to that page.

Displaying a Back Button

You can use the previous URL to display a back button on your page.

The following code demonstrates how to display a back button with a link to the previous URL:

$previous_url = $_SERVER['HTTP_REFERER'];
echo '<a href="' . $previous_url . '">Go back</a>';

Tracking User Navigation

You can use the previous URL to track user navigation on your site.

The following code demonstrates how to log the previous URL to a file:

$previous_url = $_SERVER['HTTP_REFERER'];
$file = fopen('previous_urls.txt', 'a');
fwrite($file, $previous_url . "\n");
fclose($file);

Conclusion

In this tutorial, we have explained how to get the previous URL in PHP.

We have also provided code examples to demonstrate how to use this information in your application.