IDIOT DEVELOPER

User Login System in PHP using PDO
User Login System in PHP using PDO

In the previous post, we have made  User Registration System in PHP Using PDO. In this post we going to build a User Login System in PHP Using PDO with better password encryption, which has an advantage of working on different database systems. PDO is a PHP extension that allow us to implement code which is portable across many databases and platforms.

 

User Table


CREATE TABLE `users` (
`uid` int NOT NULL PRIMARY KEY AUTO_INCREMENT ,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(200) NOT NULL 
);

Enable PDO extension for PHP, find this in php.ini configuration file.

 

Config.php

This file contains the configrations for the database connection, and has a class User, which has three methods in it – get_db(), user_login(), and, get_name().

 

The get_db() method helps in database connectivity. The user_login() helps the user in login. The get_name() method returns the user full name when provided with user id.

 


<?php 
@session_start();
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DBNAME', 'tut');
define("BASE_URL", "http://localhost/tut/pdo-login-registration/");

class User{

  function get_db(){
    try{
      $db = new PDO( 'mysql:host=' . HOST  . '; dbname=' . DBNAME, USERNAME, PASSWORD );
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      return $db;
    }catch(PDOExecption $e){
      echo 'Connection Failed: ' . $e->getMessage();
    }
  }

 function user_login($email, $password){
   try{
     $db = $this->get_db();
     $encrypt_password = hash('sha256', $password);
     $query = $db->prepare("SELECT uid FROM users WHERE email=:email AND password=:encrypt_password");
     $query->bindParam("email", $email, PDO::PARAM_STR);
     $query->bindParam("encrypt_password", $encrypt_password, PDO::PARAM_STR);
     $query->execute();
     $row_count = $query->rowCount();
     $data = $query->fetch(PDO::FETCH_OBJ);
     $db = null;
     if($row_count <= 0){
       return false;
     }else{
       $_SESSION['uid'] = $data->uid;
       return true;
     }
   }catch(PDOExecption $e){
     echo "Error: " . $e->getMessage();
   }
 }

  function get_name($uid){
    //Get the username from the userid of a user.
    $db=$this->get_db();
    try{
      $query=$db->prepare("SELECT name FROM users WHERE uid=:uid");
      $query->bindParam("uid", $uid);
      $query->execute();
      $data=$query->fetch();
      $db=null;
      return $data['name'];
    }catch(PDOException $e){
      echo "Error: " . $e->getMessage();
    }
  }
}
?>

 

 

PDO - Registration and Login in PHP

 

index.php

The index file contains the HTML and CSS code for the login page, and it also contain some PHP codes.

 


<!DOCTYPE html>
<html>
<head>
<title> PDO - Registration and Login in PHP </title>
<link rel="stylesheet" href="../../bootstrap/css/bootstrap.css">

<style type="text/css">
body{
background: #f2f2f2;
}
.main{
background:none;
width:800px;
margin-left: auto;
margin-right: auto;
margin-top:30px;
padding:0px;
}

.login{
background:#fff;
width:350px;
display:inline-block;
box-shadow: 1px 5px 10px #ccc;
padding:10px;
position: absolute;
}

.register{
background:#fff;
width:350px;
display: inline-block;
margin-left:395px;
box-shadow: 1px 5px 10px #ccc;
padding:10px;
}
</style>
</head>

<body>

<?php
$err = 0;
if(isset($_GET['err'])){
$err = ($_GET['err']);
}
?>
<h2 align="center"> PDO - Login & Registration </h2>
<div class="main">
<!-- login start -->
<div class="login">
<h3 align="center"> Login </h3>

<h4 align="center" style="color:olive;">
<?php if($err == 1){ echo 'Incorrect Username/Password'; } ?>
</h4>

<form action="login.php" method="post">
<div class="form-group">
<label for="email"> Email or Username </label>
<input type="text" class="form-control" id="email" name="email" required>
</div>

<div class="form-group">
<label for="password"> Password </label>
<input type="password" class="form-control" id="password" name="password" required>
</div>

<button type="submit" class="btn btn-primary"> Submit </button>
</form>

</div>
<!-- login ends -->

</div>

</body>
</html>

 

login.php

This file helps user in login into the application, and if the email/password are correct then it will be redirect to the home.php, otherwise the user will be redirected back to the hompage with an error message.

 


<?php
include_once('config.php');

if(isset($_POST['email'])){
$email = ($_POST['email']);
$password = ($_POST['password']);

$user = new User();
if(strlen($email) > 1 && strlen($password) > 1){
//Checking if $email and $password are not empty

$login = $user->user_login($email, $password);

if($login == false){
header('location:index.php?err=1');
//Incorrect Email or Password
}else if($login == true){
header('location:home.php');
}
}else{

}

}
?>

home.php

When the email/password are correct the user is redirected to this page.

 


<?php
include_once('session.php');
$name = $user->get_name($session_id);
?>
<!DOCTYPE html>
<html>
<head>
<title> Home </title>
<link rel="stylesheet" href="../../bootstrap/css/bootstrap.css">
<style type="text/css">
</style>
</head>

<body>
<br/><br/><br/>
<h1 align="center"> Welcome to Homepage </h1>
<br/>
<h2 align="center"> <?php echo $name ?> </h2>
<br/>
<h3 align="center"><a href="logout.php"> Logout </a></h3>
</body>
</html>

session.php

This file is used to maintain the session of the user. It contains the session variables. If the session_id  is empty or doesn’t exist then the user will be redirected to the index.php page.

 


<?php
@session_start();
$session_id = $_SESSION['uid'];
include_once('config.php');
$user = new User();
if(empty($session_id)){
header('location:index.php');
}
?>

 

logout.php

This file helps the user in logout, by destroying the session and the variables associated with it, and then redirecting the user back to the index.php page.

 


<?php
include('config.php');
session_destroy();
$session_id = '';
$_SESSION['uid'] = '';
if(empty($session_id) && empty($_SESSION['uid'])){
header('location:index.php');
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *