我正在建立一个小型的求职网站,我正在使用Nettuts.com教程中的登录系统。 登录工作正常,但我无法获取当前登录用户的详细信息,例如,如果用户输入他们的个人详细信息,我可以将数据处理到数据库,但它没有链接到哪个用户!
我理想地希望将id放入名为$ userID的变量中。
我需要一种方法来识别当前登录的用户,因此我可以将我的插入语句更新为... 'UPDATE cv where userID = $ userID'。
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
}
班级成员资格{
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, md5($pwd));
// if above = true
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['username'] = $un;
$_SESSION['password'] = $pwd;
header("location: ../myIWC.php");
} else return "Please enter a correct username and password";
}
function log_User_Out() {
if(isset($_SESSION['status'])) {
unset($_SESSION['status']);
unset($_SESSION['username']);
unset($_SESSION['password']);
if(isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time() - 1000);
session_destroy();
}
}
function confirm_Member() {
session_start();
if($_SESSION['status'] !='authorized') header("location: ../login.php");
}
$currentUN = $_SESSION['username'];
$currentPWD = $_SESSION['password'];
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT id FROM users WHERE username = ? AND password = ? LIMIT 1');
$stmt->bind_param('ss',$currentUN, $currentPWD);
$stmt->execute();
$stmt->bind_result($currentID);
}
答案 0 :(得分:0)
考虑重写您的verify_Username_and_Pass函数,以便返回用户数据数组,或编写获取它的新函数。 然后在validate_user函数中,将此数据保存到session:
$_SESSION['user_data'] = $user_data; // got from database
答案 1 :(得分:0)
嗯,我会说教程中给出的代码不是一个很好的例子。数据库类应该只是那个并且只处理数据库函数,它不应该在那里真正具有用户函数(verify_Username_and_Pass)。另外从安全角度来看,我强烈建议不要在会话中存储未加密的密码。
我很欣赏你提供的代码片段可能是更广泛实现的一部分,因此你将无法过多地使用它。因此,下面的代码将适用于您的上下文。
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT id
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
$stmt->bind_result($id);
if($stmt->fetch()) {
$stmt->close();
return $id;
} else {
return false;
}
}
}
然后在您的用户类
中if($ensure_credentials !== false) {
$_SESSION['id'] = $ensure_credentials;
$_SESSION['status'] = 'authorized';
$_SESSION['username'] = $un;
$_SESSION['password'] = $pwd;
header("location: ../myIWC.php");
} else return "Please enter a correct username and password";