Advertisement
Guest User

Untitled

a guest
Jan 6th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.22 KB | None | 0 0
  1. // index.php
  2. <?php  
  3.     require_once('authentication.php');
  4.     if (authenticateSession()) {
  5.         $username = $_SESSION['username'];
  6.         echo "<p>Welcome, " . $username . "!</p>";
  7.     }
  8.     else
  9.     {
  10.         include('login.html');
  11.     }    
  12.  
  13.     // For testing...
  14.     echo "username: " . $_SESSION['username'];
  15. ?>
  16.  
  17. // login.html
  18. <form action="login.php" method="post">
  19.     <div>
  20.         <label for="username">Username:</label>
  21.         <input type="text" name="username" value="" placeholder="Username">
  22.     </div>
  23.     <div>
  24.         <label for="password">Password:</label>
  25.         <input type="password" name="password" value="" placeholder="Password">
  26.    </div>
  27.     <input type="submit" value="Submit">
  28. </form>
  29.  
  30. // login.php
  31. <?php
  32.     require_once('authentication.php');
  33.    
  34.     if (authenticateLogin()) {
  35.         header("Location: ./index.php");
  36.     } else {
  37.         header("Location: ./index.php?err=cred");
  38.     }
  39. ?>
  40.  
  41. // authentication.php
  42. <?php
  43.     function authenticateSession() {
  44.         session_start();
  45.    
  46.         if (!isset($_SESSION['username'])) {
  47.             return false;
  48.         }
  49.        
  50.         // Otherwise, return true.
  51.         return true;
  52.     }
  53.    
  54.     function authenticateLogin() {
  55.         require_once('database.php');
  56.        
  57.         if (!isset($_POST['username']) || !isset($_POST['password'])) {
  58.             return false;
  59.         }
  60.        
  61.         $username          = $_POST['username'];
  62.         $submittedPassword = $_POST['password'];
  63.  
  64.         try {
  65.             $dbh = getPDO();
  66.             $stmt = $dbh->prepare("SELECT password FROM users WHERE username = :username");
  67.             $stmt->bindParam(':username', $username);
  68.             $stmt->execute();
  69.        
  70.             if ($stmt->rowCount() == 0) {
  71.                 return false;
  72.             }
  73.        
  74.             $row = $stmt->fetch();
  75.             $actualPassword = $row["password"];
  76.            
  77.             if ($submittedPassword != $actualPassword) {
  78.                 return false;
  79.             }
  80.        
  81.             $_SESSION['username'] = $username;
  82.             return true;
  83.              
  84.         } catch (PDOException $e) {
  85.             exit($e->getMessage());
  86.         }
  87.     }
  88. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement