我有一个会话问题。由于某种原因,会话正在设置,但会话数据未被传递。我检查了会话路径,这一切都是正确的。下面是一个登录处理程序,然后一旦用户登录就会检查会话。
我var_dumped会话并没有得到任何东西,但var_dumped两个脚本上的session_id()并得到相同的会话ID,表明正在进行会话,但由于某种原因没有传递。
感谢您的帮助。
login_handler.php
<?php
session_name("tradesman");
session_start();
include '../includes/con.inc.php';
$errors = 0;
$email_address = $_POST['tradesman_email'];
$password = $_POST['tradesman_password'];
$remember_me = $_POST['tradesman_remember_me'];
$login_check = $dbh->prepare("SELECT * FROM tradesman WHERE email_address = :email_address");
$login_check->bindParam(':email_address', $email_address);
$login_check->execute();
if($login_check->rowCount() === 1){
}else{
$response["message"] = 'denied';
$errors++;
}
if($login_check->rowCount() === 1){
while($row = $login_check->fetch()) {
$db_password = $row['password'];
$tradesman_id = $row['tradesman_id'];
$trade_name = $row['trade_name'];
$email_address = $row['email_address'];
if (password_verify($password, $db_password)) {
$update_key = $dbh->prepare("UPDATE tradesman SET token=:token WHERE tradesman_id=:tradesman_id");
$update_key->bindParam(':token', $token);
$update_key->bindParam(':tradesman_id', $tradesman_id);
if($update_key->execute()){
$token = sha1(microtime());
$_SESSION['trade_name'] = $row['trade_name'];
$_SESSION['tradesman_id'] = $row['tradesman_id'];
$_SESSION['token'] = $token;
$response["message"] = 'tradesman_login_success';
}else{
$response["message"] = 'denied';
$errors++;
}
} else {
$response["message"] = 'denied';
$errors++;
}
}
}
echo json_encode($response);
exit();
?>
account.php - 登录后(仅限会话检查)
<?php
session_name("tradesman");
session_start();
print_r($_SESSION['token']);
print_r($_SESSION['tradesman_id']);
print_r($_SESSION['trade_name']);
require_once 'includes/con.inc.php';
$session_key = $_SESSION['token'];
$check_user = $dbh->prepare("SELECT * FROM tradesman WHERE token =:session_key LIMIT 1");
$check_user->bindParam(':session_key', $session_key, PDO::PARAM_STR);
if($check_user->execute()) {
$check_user->setFetchMode(PDO::FETCH_ASSOC);
}
if($check_user->execute()){
if($check_user->rowCount() === 1){
while($row = $check_user->fetch()) {
$tradesman_id = $row['tradesman_id'];
}
}else{
header('Location:index.php');
exit();
}
}else{
header('Location:index.php');
exit();
}
?>
答案 0 :(得分:0)
问题似乎出现在你的第一个脚本中:
...
$update_key = $dbh->prepare("UPDATE tradesman SET token=:token WHERE tradesman_id=:tradesman_id");
// Here you bind the $token variable to the placeholder
$update_key->bindParam(':token', $token);
$update_key->bindParam(':tradesman_id', $tradesman_id);
// Here you execute the query, $token is not defined yet
if($update_key->execute()){
// Here you set the token, it will not be available in the database
$token = sha1(microtime());
$_SESSION['trade_name'] = $row['trade_name'];
$_SESSION['tradesman_id'] = $row['tradesman_id'];
$_SESSION['token'] = $token;
...
您可以在定义数据库之前在数据库中设置令牌,以便在数据库中设置空值。
首先定义令牌,然后将其存储在数据库和会话中。
当你绑定参数时,将它移到if
语句之前应该这样做:
...
$token = sha1(microtime());
if($update_key->execute()){
...