Posted By

daveismyname on 09/27/09


Tagged

login


Versions (?)

Who likes this?

13 people have marked this snippet as a favorite

NyX
paschim
aleksanderek
gregorio
krobichaux
tapdrup
nb109
MatthewHiggins
cjmling
adth
benediktvaldez
rmethod
clac


Login function


 / Published in: PHP
 

These functions will login a user based on a username and password being matched in a mysql database.

  1. //escape data and strip tags
  2. function safestrip($string){
  3. $string = strip_tags($string);
  4. $string = mysql_real_escape_string($string);
  5. return $string;
  6. }
  7.  
  8. //function to show any messages
  9. function messages() {
  10. $message = '';
  11. if($_SESSION['success'] != '') {
  12. $message = '<span class="success" id="message">'.$_SESSION['success'].'</span>';
  13. $_SESSION['success'] = '';
  14. }
  15. if($_SESSION['error'] != '') {
  16. $message = '<span class="error" id="message">'.$_SESSION['error'].'</span>';
  17. $_SESSION['error'] = '';
  18. }
  19. return $message;
  20. }
  21.  
  22. //log user in ---------------------------------------------------
  23. function login($username, $password){
  24.  
  25. //call safestrip function
  26. $user = safestrip($user);
  27. $pass = safestrip($pass);
  28.  
  29. //convert password to md5
  30. $pass = md5($pass);
  31.  
  32. // check if the user id and password combination exist in database
  33. $sql = mysql_query("SELECT * FROM table WHERE username = '$user' AND password = '$pass'")or die(mysql_error());
  34.  
  35. //if match is equal to 1 there is a match
  36. if (mysql_num_rows($sql) == 1) {
  37.  
  38. //set session
  39. $_SESSION['authorized'] = true;
  40.  
  41. // reload the page
  42. $_SESSION['success'] = 'Login Successful';
  43. header('Location: ./index.php');
  44. exit;
  45.  
  46.  
  47. } else {
  48. // login failed save error to a session
  49. $_SESSION['error'] = 'Sorry, wrong username or password';
  50. }
  51. }
  52.  
  53. //usage example
  54. //show any errors
  55. messages();
  56.  
  57. //pass username and password to login function the username and password would be taken from a form
  58. login($username, $password);

Report this snippet  

You need to login to post a comment.