Advertisement
Guest User

example php login

a guest
Nov 21st, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. <?
  2. $action = isset($_POST['action']) ? $_POST['action']:'';
  3. if($action == 'validatelogin')
  4. {
  5. $DbHost = "localhost";
  6. $DbDatabase = "DATABASENAME";
  7. $DbUser = "USERNAME";
  8. $DbPassword = "PASSWORD";
  9. // --- PDO Info
  10. $dsn = 'mysql:host='.$DbHost.';dbname='.$DbDatabase;
  11. $DbOptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
  12. $DBH = new PDO($dsn, $DbUser, $DbPassword, $DbOptions);
  13. $password = isset($_POST['password'])?$_POST['password']:'';
  14. $username = isset($_POST['username'])?$_POST['username']:'';
  15. if($password == ''){die('Password cannot be blank!');}
  16. if($username == ''){die('Username cannot be blank!');}
  17. $qs = "SELECT COUNT(*) as `count` FROM `users` WHERE `username`=:username";
  18. $q = $DBH->prepare($qs);
  19. $q->bindValue(':username', (string)$username, PDO::PARAM_STR);
  20. $q->execute();
  21. $count = $q->fetch(PDO::FETCH_ASSOC)['count'];
  22. if($count > 0)
  23. {
  24. $qs = "SELECT `pwhash` FROM `users` WHERE `username`=:username LIMIT 1";
  25. $q = $DBH->prepare($qs);
  26. $q->bindValue(':username', (string)$username, PDO::PARAM_STR);
  27. $q->execute();
  28. $pwhash = $q->fetch(PDO::FETCH_ASSOC)['pwhash'];
  29. if (password_verify($password, $pwhash))
  30. {
  31. //Session stuff, redirect
  32. die('Login Granted');
  33. }
  34. else
  35. {
  36. die('Invalid Username/Password');
  37. }
  38. }
  39. else
  40. {
  41. die('Invalid Username/Password');
  42. }
  43. }
  44. ?>
  45. <!doctype html>
  46. <html>
  47. <head>
  48. </head>
  49. <body>
  50. <h4 id="result"><h4>
  51. username<br>
  52. <input type="text" id="username"/><br>
  53. password<br>
  54. <input type="password" id="password"/><br>
  55. <input type="button" value="login" onclick="ajaxLogin()"/><br>
  56. <script>
  57. function ajaxLogin()
  58. {
  59. var username = encodeURIComponent(document.getElementById('username').value);
  60. var password = encodeURIComponent(document.getElementById('password').value);
  61. var params = "action=validatelogin&username="+username+"&password="+password;
  62. var url = "<?=basename($_SERVER['PHP_SELF']);?>?time="+ (new Date()).getTime();
  63. var http = new XMLHttpRequest();
  64. http.open("POST", url, true);
  65. http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  66. http.onload = function()
  67. {
  68. if(http.readyState == 4 && http.status == 200)
  69. {
  70. var result = http.response;
  71. document.getElementById('result').innerHTML = result;
  72. }
  73. };
  74. http.send(params);
  75.  
  76. }
  77. </script>
  78. </body>
  79. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement