Current Location: Home> Latest Articles> Simple PHP Code to Redirect to the Previous Page

Simple PHP Code to Redirect to the Previous Page

M66 2025-07-23

Understanding the Principle of Redirecting to the Previous Page in PHP

PHP is a widely-used server-side scripting language commonly applied in website backend development. During web development, it's common to encounter the need to redirect users back to the previous page. Since PHP runs on the server, implementing redirects requires using the HTTP protocol's redirection mechanism to instruct the browser to load a specified page.

Example of Using PHP Code to Redirect to the Previous Page

Here is a simple PHP code example that gets the referring page URL from the HTTP request headers and redirects the user to the previous page:

<?php
$referer = $_SERVER['HTTP_REFERER']; // Get the URL of the previous page
header('Location: ' . $referer); // Redirect using the header function
exit; // Ensure the script stops execution after redirect
?>

Code Explanation and Important Notes

The code uses $_SERVER['HTTP_REFERER'] to obtain the address of the page the user came from, then uses header('Location: ' . $referer) to redirect. The exit; command ensures no further code runs after the redirect.

It's important to note that HTTP_REFERER is provided by the browser and can be empty or spoofed, so it should not be fully trusted. For more secure or reliable redirection, consider using URL parameters or session variables.

Summary

This article demonstrated how to implement a PHP redirect to the previous page. Depending on your project needs, you can extend and optimize the code to ensure stable and secure redirection. We hope this helps you quickly grasp this common functionality.