Day 22: Login and Logout Functionality With OOPs.

This article is about login and logout functionality with OOPs.

There are 4 files used in this script:

1. adminCls.php Class to define member variable and functions related to Admin.

2. index.php is basically a login form, contains html and object of admin class.

3. dashboard.php it’s a secure page and available after successful login.

4. logout.php destination of logout link, session will destroy with this page and after that user will redirected to index page.

Program 65: Creation of Class

<?php
@session_start();
$con = mysql_connect(‘localhost’,’root’,”);
mysql_select_db(“mydb”,$con);
class adminCls {
var $id;
var $username;
var $password;
function login() {
$query = “select id,password from tbl_admin where username = ‘$this->username'”;
$res = mysql_query($query);
$data = mysql_fetch_array($res);
if(isset($data[‘password’]) && ($data[‘password’] == $this->password)) {
$_SESSION[‘user’] = $data[‘id’];
return true;
} else {
return false;
}
}
function logout(){
@session_start();
session_destroy();
@header(“location:index.php”);
}
}
?>

Program 66: Index Page

<?php
include_once “adminCls.php”;
$msg = “”;
$objAdmin = new adminCls();
if(isset($_REQUEST[‘btnLogin’])) {
$objAdmin->username = trim($_REQUEST[‘txtUser’]);
$objAdmin->password = trim($_REQUEST[‘txtPassword’]);
if($objAdmin->username!=”” && $objAdmin->password!=””) {
$res = $objAdmin->login();
if($res) {
@header(“location:dashboard.php”);
} else {
$msg = “Username or Password mismatch!”;
}
} else {
$msg = “Please enter valid 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 67: Secure Dashboard Page After Login

<?php
@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 functionality

<?php
include_once “adminCls.php”;
$objAdmin = new adminCls();
$objAdmin->logout();
?>