我正在开发一个简单的用户登录系统,以便在我自己的机器上练习。
我有一个带有用户名、密码和电子邮件的 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,我认为这就是我没有这样做的地方吗?
谢谢您的帮助