What are some best practices for redirecting users to a specific page after login in PHP?
When a user logs in to a website, it is often necessary to redirect them to a specific page based on their role or previous actions. One common approach is to store the target page in a session variable before the login process and then redirect the user to that page after successful authentication.
// Start the session
session_start();
// Check if the user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
// Check if a redirect page is set
if(isset($_SESSION['redirect_page'])) {
// Redirect the user to the specified page
header('Location: ' . $_SESSION['redirect_page']);
exit();
} else {
// Default redirect if no specific page is set
header('Location: index.php');
exit();
}
} else {
// Redirect to login page if user is not logged in
header('Location: login.php');
exit();
}
Keywords
Related Questions
- How can PHP foreach loops be effectively used to display dynamic data in HTML templates?
- Are there any specific server configurations or installations that could impact the performance of ImageMagick in PHP?
- In PHP, what are the benefits and drawbacks of displaying codes directly on a webpage instead of sending them via email?