以下是用户和管理员登录的登录页面
$username = trim(mysql_prep($_POST['username']));
$password = trim(mysql_prep($_POST['password']));
if (empty($errors)){
if (!$username){
$message = "username field is empty!";
}else if (!$password){
$message = "password field is empty!";
}else{
// ********** Authenticate user details ************
$cpassword = sha1($password);
$query = "SELECT * FROM users WHERE surname = '{$username}' AND password = '{$cpassword}' AND position = 'admin' LIMIT 1";
$result_set = mysql_query($query);
confirm_query($result_set);
if (mysql_num_rows($result_set) == 1){
// ********** checks the result from db *************
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['username'] = $found_user['surname'];
redirect_to("admin.php");
}else{
//redirect_to("index.php");
$message = "username or password is incorrect";
}
}
}else {
if (count($errors) == 1) {
$message = 'there was 1 error in the form';
}else {
$message = 'there were ' . count($errors) . ' errors in the form';
}
}
<form name="user" method="post" action="log.php" >
<input id="uname" type="text" name="username" placeholder="Enter your username" value="<?php echo htmlentities($username); ?>"/><br /><br />
Password:<br />
<input id="pass" type="password" name="password" placeholder="Enter your password" value="<?php echo htmlentities($password); ?>"/><br /><br />
<input id="Signin" type="submit" name="Submit" value="Sign in" /><br /><br />
</form>
答案 0 :(得分:3)
您可以从查询中删除position
子句。这样,无论是否是管理员,您都将始终返回用户。
$query = "SELECT * FROM users WHERE surname = '{$username}' AND password = '{$cpassword}' LIMIT 1";
之后,您可以在代码中检查该位置(或角色):
$result_set = mysql_query($query);
confirm_query($result_set);
if (mysql_num_rows($result_set) == 1){
$found_user = mysql_fetch_array($result_set);
$role = $found_user['position'];
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['username'] = $found_user['surname'];
if ($role == 'admin') {
redirect_to("admin.php");
}else{
redirect_to("user.php");
}
}else{
//redirect_to("index.php");
$message = "username or password is incorrect";
}
虽然上面的代码段可以解决您的问题,但此代码存在一些问题。
首先,您不应存储实际密码。很难确定,但是通过代码的外观,您可以存储实际的密码。例如,请参阅JSON-LD documentation以获取指南,让您以正确的方式开始这样做。注意这是非常重要的!密码存储不当可能导致泄密,从而导致数据丢失,员工或客户的私人数据泄露,如果您不关心,也会影响公司或您个人的声誉。
其次,您正在使用旧的mysql_*
函数,这些函数已弃用并已在PHP 7中删除。这意味着此代码甚至不会在最新的PHP上运行。
答案 1 :(得分:0)
由于根据给定的细节没有定义用户类型,我使用用户名作为条件语句。更改您的代码如下
if (mysql_num_rows($result_set) == 1){
// ********** checks the result from db *************
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['username'] = $found_user['surname'];
// Here is the logic
if( $username == 'admin' ){
header('location: admin.php');
} else {
header('location: user.php');
}
}