Day 21: login and logout functionality in PHP
Today you will see how we can use session for security purpose. In below example I have created “tbl_admin” table to store username and password inside mydb database. Below are the scripts to create table and insert record in it.
create table tbl_admin (id int primary key, username varchar(45), password varchar(45)) insert into `tbl_admin` (id,username,password) values (‘1′,’admin’,’admin’)
There are 3 files used in this script:
1. Index.php is a login page, contains html and database connectivity with session creation on successful login.
2. dashboard.php it’s a secure page and available for login user only.
3. logout.php destination of logout link, session will destroy in this page and after that user will redirected to index page.
Program 62: Login page
@session_start();
$con = mysql_connect(‘localhost’,’root’,”);
mysql_select_db(“mydb”,$con);
$msg = “”;
if(isset($_REQUEST[‘btnLogin’])) {
$user = trim($_REQUEST[‘txtUser’]);
$pass = trim($_REQUEST[‘txtPassword’]);
if($user!=”” && $pass!=””) {
$query = “select id,password from tbl_admin where username = ‘$user'”;
$res = mysql_query($query);
$data = mysql_fetch_array($res);
if(isset($data[‘password’]) && ($data[‘password’] == $pass)) {
$_SESSION[‘user’] = $data[‘id’];
@header(“location:dashboard.php”);
} else {
$msg = “Username or Password mismatch!”;
}
} else {
$msg = “Please enter username and password!”;
}
}
?>
<html>
<head><title>login</title></head>
<body>
<form method=”POST”>
<table cellspacing=”10″ align=”center” style=”border:solid 1px; padding:20px; margin-top:200px;”>
<tr><th colspan=”2″><font color=”red”><?php echo $msg; ?></font></th></tr>
<tr>
<td>Username</td> <td> <input name=”txtUser” placeholder=”username” type=”text”/> </td>
</tr>
<tr>
<td>Password</td> <td> <input name=”txtPassword” placeholder=”password” type=”password”/> </td>
</tr>
<tr>
<td></td> <td> <input name=”btnLogin” type=”submit” value=”LOGIN”/> </td>
</tr>
</table>
</form>
</body>
</html>
Program 63: Secure dashboard page after login
@session_start();
if(isset($_SESSION[‘user’]) && $_SESSION[‘user’] > 0) {
echo “<h3>Welcome To Dashboard</h3>”;
} else {
@header(“location:index.php”);
}
?>
<html>
<body>
<a href=”logout.php”>Logout</a>
</body>
</html>
Program 64: Logout page
@session_start();
session_destroy();
@header(“location:index.php”);
?>
Leave a Reply
You must be logged in to post a comment.
No Responses