Tuesday 21 June 2016

PHP Login Script using PDO with Session

This one more post on PDO tutorial, here I have discuss simple PHP login script with session by using PDO. In most of the web application for access any web application login is required. If you are using mysql or mysqli for login code. Then at that time chances of SQL Injection will increase. So I have used PDO(PHP Data Object) model for writing PHP Script for login with session this is because in PDO model is more secured that mysql or mysqli extension, because it is sql injection free. Here user information like username and password is store in one table when user enter his information then it will check the information which he was entered to information available in database, suppose information available proper then it will return one records available in database and he is authenticate to access web application and his all information is store into one session variable and with help of this session variable available on all pages of web application. When session variable expired then he will automatically logout from this website. You can find the source code on this page and you want to learn in details regarding how can we use PDO model for php login script with session, you can see the video tutorial which can be find on top of the application.


Source Code

Table


 --  
 -- Table structure for table `users`  
 --  
 CREATE TABLE IF NOT EXISTS `users` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `username` varchar(250) NOT NULL,  
  `password` varchar(250) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;  
 --  
 -- Dumping data for table `users`  
 --  
 INSERT INTO `users` (`id`, `username`, `password`) VALUES  
 (1, 'admin', 'admin');  


pdo_login.php



 <?php  
 session_start();  
 $host = "localhost";  
 $username = "root";  
 $password = "";  
 $database = "testing";  
 $message = "";  
 try  
 {  
      $connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);  
      $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
      if(isset($_POST["login"]))  
      {  
           if(empty($_POST["username"]) || empty($_POST["password"]))  
           {  
                $message = '<label>All fields are required</label>';  
           }  
           else  
           {  
                $query = "SELECT * FROM users WHERE username = :username AND password = :password";  
                $statement = $connect->prepare($query);  
                $statement->execute(  
                     array(  
                          'username'     =>     $_POST["username"],  
                          'password'     =>     $_POST["password"]  
                     )  
                );  
                $count = $statement->rowCount();  
                if($count > 0)  
                {  
                     $_SESSION["username"] = $_POST["username"];  
                     header("location:login_success.php");  
                }  
                else  
                {  
                     $message = '<label>Wrong Data</label>';  
                }  
           }  
      }  
 }  
 catch(PDOException $error)  
 {  
      $message = $error->getMessage();  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | PHP Login Script using PDO</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:500px;">  
                <?php  
                if(isset($message))  
                {  
                     echo '<label class="text-danger">'.$message.'</label>';  
                }  
                ?>  
                <h3 align="">PHP Login Script using PDO</h3><br />  
                <form method="post">  
                     <label>Username</label>  
                     <input type="text" name="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" class="form-control" />  
                     <br />  
                     <input type="submit" name="login" class="btn btn-info" value="Login" />  
                </form>  
           </div>  
           <br />  
      </body>  
 </html>  


login_success.php



 <?php  
 //login_success.php  
 session_start();  
 if(isset($_SESSION["username"]))  
 {  
      echo '<h3>Login Success, Welcome - '.$_SESSION["username"].'</h3>';  
      echo '<br /><br /><a href="logout.php">Logout</a>';  
 }  
 else  
 {  
      header("location:pdo_login.php");  
 }  
 ?>  


logout.php



 <?php   
 //logout.php  
 session_start();  
 session_destroy();  
 header("location:pdo_login.php");  
 ?>  

18 comments:

  1. Thanks for sharing helpful information useful in PHP Development

    ReplyDelete
  2. thank you so much

    ReplyDelete
  3. This instruction helped me so much! Thank you very much!!

    ReplyDelete
  4. thank:) please try another sample.

    ReplyDelete
  5. $query = "SELECT * FROM users WHERE username = :username AND password = :password";

    in above line why not use code like this " username=".$_POST["username"]." "

    ReplyDelete
  6. normally password in the database will be hashed. How to check unhashed password that user entered against hashed password stored in db?

    ReplyDelete
    Replies
    1. First you have to fetch the data from the DB, and then use the password_verify() function, in order to compare the password from the login with the one in the database.

      I just began to learn PHP a short time ago, so maybe that isn't the best solution.


      Delete
  7. Thanks for the tutorial, it's allways useful to find these kind of information.

    ReplyDelete
  8. Thanks for helping. Should I follow this code in my project?

    ReplyDelete
  9. Thank you so much! Very helpfull for me!

    ReplyDelete