Saturday, 23 November 2013

PHP Easy Sign-in Using PDO Prepared Statement Tutorial


Source is here
In software systems or web based systems developed by us, we have to secure some pages from unauthorized access and for that purpose we will protect these pages. These pages can be for Admin members or registered members and only those can see them. For giving members rights we will often give them username and password and when they give these values, they are redirected to secret pages.
PHP easy sign-in using PDO prepared statement tutorial will teach you how to make a log in system using PDO (PHP Data Objects) queries. This tutorial contains very basics and easy steps so anyone can understand it and implement it. Source code for sign-in tutorial is also available for you. We will use bootstrap as CSS Framework with PHP and MySQL. We will also understand how to protect pages from unauthorized access if someone knows the link and directly type in browser. This tutorial will teach you following
  • How to make a Sign in Form.
  • How to create a Members Table.
  • How to make a Connection Page
  • How to check a User Details for Authentication.
  • How to redirect a Registered User.
  • How to protect a User Page.
  • How to make a User Session Page.
  • How to make a Logout Page.
Source Code Zip Folder contains following files and folders, below is the explanation of each.
  • sql.txt contains full database structure along with sample data.
  • index.php is file from where you can login to system
  • AdminIndex.php is a page which will open after successful login.
  • CheckLogin.php is a file which will check the username and password and redirect to secret pages like AdminIndex.php
  • configPDO.php is a file which will create connection with database.
  • NavButtons.php is a file which contains menu list for this system.
  • Footer.php is a file which contains footer bar and forms for sign in, password update and server information addition.
  • Logout.php is a file which will destroy the session and logout the user to index.php page.
  • UserSessionAdmin.php is a file which included for protection of pages from unauthorized users.
  • assets folder contains necessary css, icon, images and js files.
  • OPEN-TICKET-EXCEL.php is a file which will export data in Excel.
  • We use Jquery Bootstrap plugin for sign in form. You can learn more aboutjqBootstrapValidation.
We use following for developing PHP easy sign-in using PDO prepared statement tutorial in which EXPORT To EXCEL option using PDO also included.
  • PHP as Server Side Scripting Language
  • MySQL as a Database.
  • Bootstrap as CSS Framework.
  • JQuery as a service.
  • jqBootstrapValidation for validating sign-in form.
  • phpMyAdmin for creating database and tables.
  • Sublime Text 2+ as a code editor.
  • XAMPP as a package for Apache web server, PHP and MySQL.
  • Google Chrome as a browser for testing.
  1. First we will make a sign-in button in index.php page and use data-toggle as modal and give href value as #signin
    • <a href="#signin" data-toggle="modal" class"btn btn-primary btn-large">Sign In</a>
      
  2. When we press sign in button, modal will be open which will display below form for sign in. Form code is in footer.php page and its a part of index.php page.
    • <div id="signin" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h3 id="myModalLabel">Sign In Form</h3>
                  </div>
                  <div class="modal-body">
      <form class="form-horizontal" method="post" action="CheckLogin.php">
                  <div class="control-group">
                    <label class="control-label" for="inputName">User Name</label>
                    <div class="controls">
                      <input type="text" name="inputName"  id="inputName" placeholder="User Name" required="required">
                    </div>
                  </div>
                  <div class="control-group">
                    <label class="control-label" for="inputPassword">Password</label>
                    <div class="controls">
                      <input type="password" name="inputPassword" id="inputPassword" placeholder="Password" maxlength="15" minlength="6"  required="required">
                    </div>
                  </div>
                  <div class="control-group">
                    <div class="controls">
                      <button type="submit" class="btn">Sign in</button>
                    </div>
                  </div>
                </form>
      
                  </div>
                </div>
  3. Before sending username and password to CheckLogin.php we will create signinpdo database using sql.txt file which contains below tables create queries and sample data for demo and test.
    • members table contains members details like MemId, UserName, Password, Type, Region.
    • ttmain table contains fields like SrNo, TTDescription, TTCity, TTEntryDate, TTEntryTime, TTEntryBy, TTClosedDate, TTClosedTime, TTClosedBy, Status.
    Table Structure for Members Table
  4. configPDO.php file use a PDO (PHP Data Objects) for connection to MySQL Databaseto avoid SQL injections.
    • <?php
      // mysql hostname
      $hostname = 'localhost';
      // mysql username
      $username = 'root';
      // mysql password
      $password = '';
      // Database Connection using PDO
      try {
      $dbh = new PDO("mysql:host=$hostname;dbname=signinpdo", $username, $password);
          }
      catch(PDOException $e)
          {
          echo $e->getMessage();
          }
      ?>
  5. CheckLogin.php page compare username and password with MySQL Members table username and password and if its successful redirects to protected page named AdminIndex.php. If username and password not authenticated and unsuccessful it will redirect user to index.php page.
    • Important Note: This tutorial is about sign-in, so if you want to protect passwords please use md5 function or any other way. Storing plain passwords in database might be risky.
    • <?php
      // Start Session because we will save some values to session varaible.
      session_start();
      // include connection file
      include("configPDO.php");
      // Define $myusername and $mypassword
      $UserName=$_POST['inputName']; 
      $Password=$_POST['inputPassword']; 
      // We Will prepare SQL Query
          $STM = $dbh->prepare("SELECT Type,Region FROM members WHERE UserName = :UserName AND Password = :Password");
      // bind paramenters, Named paramenters alaways start with colon(:)
          $STM->bindParam(':UserName', $UserName);
          $STM->bindParam(':Password', $Password);
      // For Executing prepared statement we will use below function
          $STM->execute();
      // Count no. of records 
      $count = $STM->rowCount();
      //just fetch. only gets one row. So no foreach loop needed :)
      $row  = $STM -> fetch();
      // User Redirect Conditions will go here
       if($count==1)
       
       {
           // Save type and other information in Session for future use.
        $_SESSION[type]=$row[0];
        $_SESSION[Region]=$row[1];
        $_SESSION[myusername]=$UserName;
        
        // if user type is ACTAdmin only then he can access protected page.
        if($row[0] == 'ACTAdmin')  { header( "location:http://localhost/SimpleSignInPDO/AdminIndex.php");  }
        else    { header( "location:http://localhost/SimpleSignInPDO/index.php");  }
      
       }
       else 
       {
       header("location:http://localhost/SimpleSignInPDO/index.php");
       }
      // Closing MySQL database connection 
          $dbh = null;
      ?>
  6. For protection of pages we include UserSessionAdmin.php file at the top of each protected page.
    • <?php
      include('UserSessionAdmin.php');
      ?>
  7. Below is code for UserSessionAdmin.php. We use Type of the user in this file to protect pages.
    • <?php
      session_start();
      if($_SESSION[type]!='ACTAdmin'){
      header('location:index.php');
      exit();
      }
      include('configPDO.php');
      ?>
    Thanks for reading. Enjoy and share with friends.
We hope you will find PHP easy sign-in using PDO prepared statement tutorial very helpful and easy. PDO (PHP Data Objects) Prepared statements used in this tutorial along with Bootstrap CSS Framework. For any query/suggestions please post a comment on ourFacebook Page.