Advertisement
gitlez

YA: Simple Login WC

Apr 11th, 2012
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.84 KB | None | 0 0
  1. <?php
  2. // Post in response to a Yahoo Answer's Question
  3. session_start();
  4.  
  5. $username = $_POST['username'];
  6. $password = $_POST['password'];
  7.  
  8. if ($username && $password){
  9.     // Good job on the informative error messages.
  10.     $connect = mysql_connect("127.0.0.1","root","") or die ("Couldnt Connect to Database");
  11.     mysql_select_db("login", $connect) or die ("Couldnt find database");
  12.     // Prevent MySQL Injection Attacks, Google it.
  13.     $username = mysql_real_escape_string( $username );
  14.     $password = mysql_real_escape_string( $password );
  15.    
  16.     $query = mysql_query("SELECT username FROM users WHERE username='$username' AND password='$password' LIMIT 1");
  17.     // The query only needs to return the username, because that is the only information you need. Returning additional information uses
  18.     // additional resources. Also, the query can check for the password combination, saving you time and effort. LIMIT 1 simply tells MySQL to
  19.     // stop looking once it finds the one result it needs. Speed and resources.
  20.     if($query && mysql_num_rows($query) === 1){ // Checks for a successful query and that the number of rows returned is equal to 1.
  21.         $_SESSION['username'] = mysql_fetch_object($query)->username;
  22.         echo "Login successful. <a href='membersarea.php'>Click here to enter the member area</a>";
  23.     } else {
  24.         // Never tell the user that the username is correct but the password is incorrect. People can then brute force attack a particular username.
  25.         // A simple combination error will usually let people know that there is a problem with their password.
  26.         echo 'Incorrect Username/Password Combination. <a href="' . $_SERVER['HTTP_REFERER'] . '">Click Here To Return</a>.';
  27.     }
  28.     mysql_close( $connect ); // Good Idea to close the connections.
  29. }else{
  30.     die('Please enter a username and password. <a href="' . $_SERVER['HTTP_REFERER'] . '">Click Here To Return</a>.');
  31. }
  32. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement