Home > Article > Backend Development > How to Redirect Users Back to Their Previous Page After Successful Login?
When a user logs in to a website, it's often desirable to redirect them back to the page they were previously browsing. This provides a seamless user experience and eliminates the need for manual navigation after login.
To achieve this goal, a common approach is to pass the user's current page URL as a $_GET variable to the login form. For instance, if a user is on the article page "comment.php?articleid=17" when they attempt to leave a comment, the URL would include the current location.
The login page (login.php) should then check for the presence of $_GET['location']. If it exists, the page can redirect the user to that specific URL after successful login. Here's how you can implement it:
In login.php:
<code class="php">echo '<input type="hidden" name="location" value="'; if(isset($_GET['location'])) { echo htmlspecialchars($_GET['location']); } echo '" />';</code>
This hidden input field stores the current page URL and sends it along with the login form submission.
In login-check.php:
<code class="php">session_start(); $redirect = NULL; if(isset($_POST['location']) && $_POST['location'] != '') { $redirect = $_POST['location']; } if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) { $url = 'login.php?p=1'; if(isset($redirect)) { $url .= '&location=' . urlencode($redirect); } header("Location: " . $url); exit(); } elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) { $url = 'login.php?p=2'; if(isset($redirect)) { $url .= '&location=' . urlencode($redirect); } header("Location:" . $url); exit(); } elseif(isset($_SESSION['id_login'])) { if($redirect) { header("Location:". $redirect); } else { header("Location:login.php?p=3"); } exit(); }</code>
In this login-check.php script:
This mechanism allows for smooth redirection to the page the user was browsing before login, enhancing the user experience and simplifying the login process.
The above is the detailed content of How to Redirect Users Back to Their Previous Page After Successful Login?. For more information, please follow other related articles on the PHP Chinese website!