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.
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
?>
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.
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.