Advertisement
CFHeadphase

do_login

May 27th, 2018
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.83 KB | None | 0 0
  1. <!-- Backend page. Checks login against database, then generates SESSION -->
  2. <?php
  3. // Include MySQL connection object ($db)
  4. include 'connect_mysql.php';
  5.  
  6. // Debug code -- Show errors
  7. error_reporting( E_ALL );
  8. ini_set( "display_errors", 1 );
  9.  
  10. // Get POSTed variables
  11. $username = $_POST["username"];
  12. $password = $_POST["password"];
  13.  
  14. // Main execution block
  15. checkInputs();
  16. if (checkLogin($username, $password) == 1) {
  17.     // Generate session
  18.     generateSession(getUserID($username));
  19. } else {
  20.     // TODO: Redirect to failure page
  21.     die("The login entered was incorrect. Please try again.");
  22. }
  23.  
  24. // Checks if POST variables were passed in
  25. function checkInputs() {
  26.     if(empty($_REQUEST['username'])) {
  27.         //TODO: Replace with error page.
  28.         die("Username was missing. Please try again.");
  29.     }
  30.     elseif(empty($_REQUEST['password'])) {
  31.         //TODO: Replace with error page.
  32.         die("Password was missing. Please try again.");
  33.     }
  34. }
  35.  
  36. // Returns whether the entered login is valid
  37. function checkLogin($username, $password) {
  38.     /*
  39.     Return row number of a valid login.
  40.     Checks password hashes for security purposes.
  41.     */
  42.    
  43.     $hashPass = password_hash($password, PASSWORD_DEFAULT);
  44.    
  45.     $query = ("SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'");
  46.    
  47.     $result = mysql_query($query, $db) or die("Could not execute query: " . mysql_error());
  48.     $numRows = mysql_num_rows($result);
  49.  
  50.     if ($numRows != 0) {
  51.         return 1; // Query success
  52.     } else {
  53.         return 0; // Query failure
  54.     }
  55. }
  56.  
  57. function generateSession($userID) {
  58.     session_start();
  59.     $_SESSION["userID"] = $userID;
  60. }
  61.  
  62. function getUserID($username) {
  63.     $query = ("SELECT 'id' FROM 'users' WHERE 'username' = '" . $username . "'");
  64.     $result = mysql_query($db, $query);
  65.    
  66.     if ($result !== false) {
  67.     $id = mysqli_fetch_field($result);
  68.     }
  69.    
  70.     return $id;
  71. }
  72. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement