PHP Session and page redirect based on user login
From w3cyberlearnings
Contents |
Usage
- using session to implement user login.
- redirect user based on the user login information to different page.
- implement user logout with session_destroy();
login.php
- Contain the HTML form for user to login
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <form action="action.php" method="post"> <h3> Login</h3> Login Name: <input type="text" name="login_name"/><br/> Password: <input type="password" name="login_password"/><br/> <input type="submit" name="submitlogin" value="Login"/> </form> </body> </html>
action.php for processing the login.php form
- This section implements the login logic.
- This page will redirect user according to the user login name.
- You can use this example with database to authenticate user and redirect user accordingly.
- Admin user will redirect to the admin.php page.
- All other users will redirect to the user.php page.
<?php //session start session_start(); // check for submit if (!empty($_POST['submitlogin'])) { // assign form data to the session $_SESSION['login_name'] = $_POST['login_name']; $_SESSION['login_password'] = $_POST['login_password']; // check the user information and perform the redirect if (isset($_SESSION['login_name']) && $_SESSION['login_name'] == "bob") { header("Location:admin.php"); } else { header("Location:user.php"); } } ?>
admin.php page
- This page for admin user (only for bob)
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Admin Page</title> </head> <body> <?php session_start(); $name = ""; if (isset($_SESSION['login_name'])) { $name = $_SESSION['login_name']; } ?> Welcome to Admin Page! <p>Hello <?php echo $name; ?></p> <a href="logout.php">Logout</a> </body> </html>
user.php page
- This page for normal user
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Page</title> </head> <body> <?php session_start(); $name = ""; if (isset($_SESSION['login_name'])) { $name = $_SESSION['login_name']; } ?> Welcome to User Page! <p>Hello <?php echo $name; ?></p> <a href="logout.php">Logout</a> </body> </html>
logout.php for user log out page
- When user logout, it will redirect user back to the login.php page.
<?php session_start(); session_destroy(); header("Location:login.php"); ?>