Home > Article > Backend Development > How to Redirect Users Back to Their Previous Page After Login?
Redirecting to the Previous Page After Login
When a user logs into a website, it's often desirable to redirect them back to the page they were previously browsing. This ensures a seamless user experience and eliminates the need for them to manually navigate back.
One way to implement this functionality is to pass the user's current location via a GET variable when redirecting them to the login page:
<code class="php">header("Location:login.php?location=" . urlencode($_SERVER['REQUEST_URI']));</code>
This will send the user to a login page that includes a hidden input field containing the URL of the previous page:
<code class="php">echo '<input type="hidden" name="location" value="'; if(isset($_GET['location'])) { echo htmlspecialchars($_GET['location']); } echo '" />';</code>
In the login-check.php script that processes the login request, if the login is successful and the location parameter is set, the user is redirected to the stored URL:
<code class="php">if(isset($_POST['location'])) { $redirect = $_POST['location']; } // ... if(isset($_SESSION['id_login'])) { // if login is successful and there is a redirect address, send the user directly there if($redirect) { header("Location:". $redirect); } }</code>
However, it's crucial to perform validation on the $_GET['location'] parameter to prevent users from being redirected to malicious websites. Additionally, always use urlencode when passing URLs as GET parameters to handle special URL characters correctly.
The above is the detailed content of How to Redirect Users Back to Their Previous Page After Login?. For more information, please follow other related articles on the PHP Chinese website!