irwan

User Login with Cookies

Nov 20th, 2011
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.84 KB | None | 0 0
  1. Creating the Login Form:
  2.  
  3. <form name="login" action="login.php" method="post">
  4.   Username: <input type="text" name="username" size="30" maxlength="255" /><br/>
  5.   Password: <input type="password" name="password" size="30" maxlength="255" /><br/>
  6.   <input type="submit" value="Login" />
  7. </form>
  8.  
  9. Creating the login.php file:
  10. The login.php file will check to see that the username and password that have been entered into the form are valid. If they are, we will set a cookie with their information. This script assumes you are storing your passwords in the database using SHA1. Here is what login.php will look like:
  11.  
  12. <?php
  13.  
  14.   //include the database connection here...
  15.  
  16.   //convert username to uppercase... make it non-case sensitive.
  17.   //then use the MD5 algorithm on the password
  18.   $username = strtoupper($_POST['username']);
  19.   $password = SHA1($_POST['password']);
  20.  
  21.   //query to run to database.  also converts username to uppercase.
  22.   //counts how many times the username and password match (will either be 0 or 1)
  23.   $query = "select * FROM users WHERE
  24.      UPPER(username) = '$username' AND
  25.      password = '$password'";
  26.  
  27.   $result = mysql_query($query);
  28.   $count = mysql_num_rows($result);
  29.    
  30.   if ($count > 0)
  31.   {
  32.     //the username and password match.  we can now store the userid and password in the cookie.
  33.     //we can use this for subsequent pages to figure out who the user is.
  34.     $result = mysql_fetch_array($result);
  35.     $userId = $result['userid'];
  36.  
  37.     //set the cookie
  38.     setcookie("userId", $userId, time()+60*60*24*30);
  39.     setcookie("userPass", $password, time()+60*60*24*30);
  40.  
  41.     //let them know they're logged in now.
  42.     echo 'You are now logged in!';
  43.   }
  44.   else
  45.   {
  46.     //something wasn't right, so we can't log them in.
  47.     echo 'Either your username or password were not correct.  Try again.';
  48.   }
  49. ?>
  50.  
Advertisement
Add Comment
Please, Sign In to add comment