1

我正在开发一个简单的用户登录系统,以便在我自己的机器上练习。

我有一个带有用户名、密码和电子邮件的 mysql 表用户。我能够使用以下内容注册新用户:

//short variable names:

$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

session_start();

//attempt to register
register($username, $email, $password); 

我创建了这个函数来输入 db 它使用以下函数工作:

 function register($username, $email, $password){
//register new person with db
//return true or error

//connect to db
$db = db_connect();

//check if username is unique
$result = $db->query("SELECT * from user where username = '".$username."'");
if(!$result){
    throw new Exception('Could not execute query');
}

if($result->num_rows>0){
    throw new Exception('That username is taken - go back and choose another one.');
}

//if ok, put in db
$result = $db->query("INSERT into user values
        ('".$username."', sha1('".$password."'), '".$email."')");

if(!$result){
    throw new Exception('Could not register you in database - Please try again later.');
}

return true;

}

然后我注册了变量

//register session variable
$_SESSION['valid_user'] = $username;

echo 'Your registration was successful. Go to the members page to start setting up your profile!';

当我尝试使用用户名和密码登录时,它不起作用这里是登录代码:

function login($username, $password){
//check username and password with db
$db = db_connect();

//check if username unique
$result = $db->query("SELECT * FROM user where username = '".$username."' and password = sha1('".$password."')");
if(!$result){
    throw new Exception('Could not log you in.');
}
if($result->num_rows > 0){
    return true;
} else {
    throw new Exception('Could not log you in.');
}
}

我知道这不安全,只是在我的机器上练习,所以我可以向上移动,有人有什么解释吗?密码在数据库中注册为 sha1 varchar,我认为这就是我没有这样做的地方吗?

谢谢您的帮助

4

2 回答 2

1

问题很可能出在密码的VARCHAR定义中。sha1的长度为 160 位。

无论如何,我不建议在VARCHAR字段中存储密码,而是使用BINARY(20)UNHEX函数将SHA1值转换为二进制。

数据库中有很多记录(数千,数百万)二进制(20)比varchar或char占用更少的内存。

将其更改为CHAR(40)

于 2013-03-19T21:25:25.553 回答
-1

尝试

function login($username, $password){
//check username and password with db
$db = db_connect();

//check if username unique
$result = $db->query("SELECT * FROM user where username = '".$username."' and password = sha1('".$password."')");
if(!$result){
    throw new Exception('Could not log you in.');
}
if(mysql_num_rows($result) > 0){
    return true;
} else {
    throw new Exception('Could not log you in.');
}
}

我更改了您的条件检查 num 行。

于 2013-03-19T21:32:57.647 回答