密码加密登录问题

时间:2013-02-20 05:05:41

标签: php mysql encryption login

我在我的sql数据库中查找和验证用户的加密密码时遇到问题。注册过程很好,它使用md5 ecrypted密码创建行,但是当尝试登录时,它将无法识别他们的密码。继续使用的是:

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$myusername = $_POST['myusername']; 
$mypassword = $_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='md5($mypassword)'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
session_start();
$_SESSION['login'] = "$myusername";

3 个答案:

答案 0 :(得分:0)

尝试

mysql_connect($host, $username, $password)or die("cannot connect"); 
mysql_select_db($db_name)or die("cannot select DB");

// username and password sent from form 
$myusername = $_POST['myusername']; 
$mypassword = $_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM '".$tbl_name.". WHERE username='".$myusername."' and password='".md5($mypassword)."'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
session_start();
$_SESSION['login'] = $myusername;

答案 1 :(得分:0)

用以下内容替换你的$ sql。我假设你在$ tbl_name -variable中有正确的表名。

$sql="SELECT * FROM ".$tbl_name." WHERE username='".$myusername."' and password='".md5($mypassword)."'";

答案 2 :(得分:0)

大声笑你的代码是复杂的,我提供的脚本不好!

使用STMT意味着没有SQL注入

如何加密密码(正确的方法!!!)

function Encrypt($text) {
  $cost = 12;
  $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
  $salt = sprintf("$2a$%02d$", $cost) . $salt;
  $altered_text = crypt($text, $salt);
  return $altered_text;
}

// Then use the code below to use the function

$password = Encrypt($password);

在登录时请使用强力保护

这是一个暴力保护代码

function BruteForce($user_id, $link) {
    $now = time();
    $timespan = $now - (2 * 60 * 60);
    if ($stmt = $link->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$timespan'")) {
        $stmt->bind_param('i', $user_id);
        $stmt->execute();
        $stmt->store_result(); 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
        $stmt->close();
    }
}

然后使用下面的sql语句

CREATE TABLE `login_attempts` (
    `user_id` INT(11) NOT NULL,
    `time` VARCHAR(30) NOT NULL
) ENGINE=InnoDB

然后存储尝试

function StoreAttempt($user_id, $link) {
    $now = time();
    $stmt = $link->prepare("INSERT INTO login_attempts (user_id, time) VALUES (?, ?)");
    $stmt->bind_param("ss", $a, $b);
    $a = $user_id;
    $b = $now;
    $stmt->execute();
    $stmt->close();
}

然后在行动中使用它

// user_id = the users id after you get the users id
// link = the database connection

if (BruteForce($user_id, $link) === true) {
    // Too many login attempts
} else {
    // Store Attempt
    StoreAttempt($user_id, $link);
}

我建议您使用安全会话而不是普通会话

使用以下代码

function SecureSession() {
    $session_name = 'SecureSession';
    $secure = true;
    $httponly = true;
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        die("Could not initiate a safe session (ini_set)");
    }
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
    session_name($session_name);
    session_start(); 
    session_regenerate_id(true);
}

立即开始会话

SessionSecure();

如果您打算使用PHP SELF

使用以下代码

function SanitizeUrl($url) {
    if ('' == $url) {
        return $url;
    }
    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url); 
    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;
    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }
    $url = str_replace(';//', '://', $url);
    $url = htmlentities($url);
    $url = str_replace('&', '&', $url);
    $url = str_replace("'", ''', $url);
    if ($url[0] !== '/') {
        return '';
    } else {
        return $url;
    }
}

上面的函数是针对PHP SELF ex的保护

然后使用它

SanitizeUrl($_SERVER['PHP_SELF']);

现在为实际的登录功能

我建议您在登录时使用电子邮件然后使用用户名主要是因为您的电子邮件不是唯一的

function Login($email, $password, $link) {
    if (empty($username) || empty($password)) {
        // A field is empty
        return false;
    } else {
        $sql = "SELECT `id`,`username`,`password` FROM `users` WHERE `email` = ?";
        if ($stmt = $link->prepare($sql)) {
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows == 1) {
                $stmt->bind_result($db_id, $db_username, $db_password);
                $stmt->fetch();
                if (BruteForce($db_id, $link) === false) {
                    $password = Encrypt($password);
                    if ($password == $db_password) {
                        // LOGGED IN, SET SESSION VARS
                        return true;
                    } else {
                        // Store Attempt
                        StoreAttempt($user_id, $link);
                        return false;
                    }
                } else {
                    return false
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}

然后在行动中使用它

SessionSecure();

if (isset($_POST['DoLogin'])) {
   $email = $_POST['login-email'];
   $password = $_POST['login-password'];
   if (Login($email, $password, $link) === true) {
       // Logged in Redirect now!
   } else {
       // Login failed
   }
}

随意使用此代码! :)