Posted By

ecavazos on 01/22/08


Tagged

login session password start md5


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

mbcdg
crs0328
kdnewman
MatthewHiggins


Login & Start Session


 / Published in: PHP
 

  1. <?php
  2. // start session
  3. if (array_key_exists('username', $_SESSION)) {
  4. // user already authenticated
  5. header('location: index.php');
  6. }
  7.  
  8. if ($_POST) {
  9.  
  10. if (array_key_exists('username', $_POST)) {
  11. require_once('codes/dal.php');
  12. $dal = new DataAccessLayer();
  13.  
  14. $user = trim($_POST['username']);
  15. $pass = trim($_POST['password']);
  16. $pass = bin2hex(md5($pass, TRUE ));
  17.  
  18. // join the 'users' and 'roles' tables
  19. $sql = 'select '
  20. . 'u.id '
  21. . ',u.username '
  22. . ',u.password '
  23. . ',u.role_id '
  24. . ',r.name '
  25. . ',u.full_name '
  26. . ',u.email '
  27. . ',u.description '
  28. . 'from users as u '
  29. . 'join roles as r on u.role_id = r.id '
  30. . 'where u.username = \'' . $user . '\'';
  31.  
  32. $result = $dal->query($sql);
  33.  
  34. if ($result->num_rows > 0) {
  35. $row = $result->fetch_assoc();
  36. if ($pass == $row['password']) {
  37. // create session variables
  38. $_SESSION['user_id'] = $row['id'];
  39. $_SESSION['username'] = $row['username'];
  40. $_SESSION['full_name'] = $row['full_name'];
  41. $_SESSION['role_id'] = $row['role_id'];
  42. $_SESSION['role_name'] = $row['name'];
  43. $_SESSION['email'] = $row['email'];
  44. $_SESSION['password'] = $row['password'];
  45.  
  46. // check if password is default
  47. if($pass == bin2hex(md5('pass', TRUE ))) {
  48. $_SESSION['default'] = true;
  49. // login successful - but password needs to be changed
  50. header('location: users/change_password.php');
  51. } else {
  52. // login successful - redirect to home page
  53. header('location: index.php');
  54. }
  55. } else {
  56. $err = '<tr><td colspan="2">'
  57. . '<div class="error-message">The username and/or password you entered is invalid.</div>'
  58. . '</td></tr>';
  59. }
  60.  
  61. } else {
  62. $err = '<tr><td colspan="2">'
  63. . '<div class="error-message">The username and/or password you entered is invalid.</div>'
  64. . '</td></tr>';
  65. }
  66. }
  67. }
  68. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: rabbitt on May 5, 2008

You forgot to sanitize your inputs here ($user in particular). It wouldn't be hard to inject some sql into $user and login as another user. You should /always/ be sure to sanitize/quote your data before passing it off to the database.

You need to login to post a comment.