PHP$\u会话和$\u COOKIE奇怪的行为
我正在尝试将Cookie安装到我的网站中。PHP$\u会话和$\u COOKIE奇怪的行为,php,session,cookies,Php,Session,Cookies,我正在尝试将Cookie安装到我的网站中。 我在GitHub上找到了一个脚本: 我已经实现了脚本,并且可以登录。 我可以只使用会话登录,也可以同时使用两个会话登录,并设置“记住我-COOKIE”。 为了测试COOKIE,我将会话设置为1分钟后过期$expireAfter=1 塞纳里奥: 我登录到网站并选中“记住我”。会话启动并设置cookie。一切都好 ##最后一个操作:1秒前 跳过cookie检查:会话已设置 我等待60秒,然后重新加载页面。会话销毁和Cookie读取: ##最后一个动作:10
我在GitHub上找到了一个脚本:
我已经实现了脚本,并且可以登录。
我可以只使用会话登录,也可以同时使用两个会话登录,并设置“记住我-COOKIE”。
为了测试COOKIE,我将会话设置为1分钟后过期<代码>$expireAfter=1代码>
塞纳里奥:
我登录到网站并选中“记住我”。会话启动并设置cookie。一切都好
##最后一个操作:1秒前
跳过cookie检查:会话已设置
我等待60秒,然后重新加载页面。会话销毁和Cookie读取:
##最后一个动作:108秒前
不活动的会话销毁
曲奇饼阅读
cookie有效格式
cookie右选择器
cookie权利令牌
在DB和cookie中设置新令牌
会话集
我想我找到了问题。取消设置并销毁会话后。我必须开始新的课程。
奇怪的是,这种事只会每秒钟发生一次。但是添加
session_start()代码>解决了问题
if(isset($_SESSION['last_action'])){
$secondsInactive = time() - $_SESSION['last_action'];
$expireAfterSeconds = $expireAfter * 60;
$debug.="last action: $secondsInactive seconds ago<br>";
if($secondsInactive >= $expireAfterSeconds){
//User has been inactive for too long.
//Kill their session.
session_unset();
session_destroy();
$debug.="session destroy for inactivity<br>";
}
}
...
session_start();
$_SESSION['user'] = $session_data;
...
if(isset($\u会话['last\u action'])){
$secondsInactive=time()-$\会话['last\ u action'];
$expireAfterSeconds=$expireAfter*60;
$debug.=“上次操作:$secondsInactive秒前
”;
如果($secondsInactive>=$expireAfterSeconds){
//用户处于非活动状态的时间太长。
//终止他们的会话。
session_unset();
会话_destroy();
$debug.=“会话因不活动而销毁
”;
}
}
...
会话_start();
$\u会话['user']=$SESSION\u数据;
...
<?php
define ("PEPPER",''); //random string for extra salt, use if you want.
define ("WEBSITE",'mydomain.com'); //your web site without http:// without final /
define ("SCRIPTFOLDER",'/login'); //direcory of the script start with a / if you installed the script in the root write just a / never finish with a /
$hosting="localhost"; //your host or localhost
$database="db"; //your database name
$database_user="user"; //your username for database
$database_password="pwd"; //your database password
require_once('pdo_db.php');
//generate random sequence or numbers and letter avoid problems with special chars
function aZ ($n=12) {
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$bytes = random_ver($n);
$result="";
foreach (str_split($bytes) as $byte) $result .= $chars[ord($byte) % strlen($chars)];
return $result;
}
//generate random and avoid compatibility problem with php version
function random_ver ($n=10) {
$v=(int)phpversion()+0;
if ($v<7) {
//if php version < 7 use the old function for generate random bytes
return openssl_random_pseudo_bytes($n);
}else{
//random_bytes is better but works only with php version > 7
return random_bytes($n);
}
}
// ********************************
// * SESSION TIME UPDATE *
// ********************************
//Expire the session if user is inactive for 15 minutes or more.
//if u want to check how cookie works let the session id expire (wait X minutes without action, maybe set expireAfter to low value),
//close the browser then open again
$expireAfter = 1;
//Check to see if our "last action" session
//variable has been set.
if(isset($_SESSION['last_action'])){ echo 'IN';
//Figure out how many seconds have passed
//since the user was last active.
$secondsInactive = time() - $_SESSION['last_action'];
//Convert our minutes into seconds.
$expireAfterSeconds = $expireAfter * 60;
//Check to see if they have been inactive for too long.
$debug.="last action: $secondsInactive seconds ago<br>";
if($secondsInactive >= $expireAfterSeconds){
//User has been inactive for too long.
//Kill their session.
session_unset();
session_destroy();
$debug.="session destroy for inactivity<br>";
}
}
//Assign the current timestamp as the user's
//latest activity
$_SESSION['last_action'] = time();
// *********************************
// * CHECK AUTO LOG-IN WITH COOKIE *
// *********************************
//if session is not set, but cookie exists
if (empty($_SESSION['user']) && !empty($_COOKIE['remember']) && $_GET["logout"]!=1) {
$debug.="cookie read<br>";
list($selector, $authenticator) = explode(':', urldecode($_COOKIE['remember']));
//get from database the row with id and token related to selector code in the cookie
$sql = $db->prepare("SELECT * FROM user_tokens
WHERE selector = ? limit 1");
$sql->bindParam(1, $selector);
$sql->execute();
$row = $sql->fetch(PDO::FETCH_ASSOC);
if (empty($authenticator) or empty($selector))
$debug.="cookie invalid format<br>";
//continue to check the authenticator only if the selector in the cookie is present in the database
if (($sql->rowCount() > 0) && !empty($authenticator) && !empty($selector)) {
$debug.="cookie valid format<br>";
// the token provided is like the token in the database
// the functions password_verify and password_hash add secure salt and avoid timing attacks
if (password_verify(base64_decode($authenticator), $row['hashedvalidator'])){
//SET SESSION DATA
$sql = $db->prepare("SELECT * FROM users WHERE id = ?");
$sql->bindParam(1, $row['userid']);
$sql->execute();
$session_data = $sql->fetch(PDO::FETCH_ASSOC);
//UNSET VARS
unset($session_data['password']);
$_SESSION['user'] = $session_data;
//update database with a new token for the same selector and set the cookie again
$authenticator = bin2hex(random_ver(33));
$res=$db->prepare("UPDATE user_tokens SET hashedvalidator = ? , expires = FROM_UNIXTIME(".(time() + 864000*7).") , ip = ? WHERE selector = ?");
$res->execute(array(password_hash($authenticator, PASSWORD_DEFAULT, ['cost' => 12]),$_SERVER['REMOTE_ADDR'],$selector));
//set the cookie
$setc = setcookie(
'remember',
$selector.':'.base64_encode($authenticator),
time() + 864000*7, //the cookie will be valid for 7 days, or till log-out (if u want change it, modify the login.php file too)
'/',
WEBSITE,
false, // TLS-only set to true if u have a website on https://
false // http-only
);
$debug.="cookie right selector<br>cookie right token<br>set a new token in DB and in cookie<br>session set ".$_SESSION['user']['usr_fname']."<br>";
} else {
//selector exists but token doesnt match. that could be a secure problem, all selector/authenticator in database for that user will be deleted
$res=$db->prepare("DELETE FROM user_tokens WHERE userid = ".$row["userid"]);
$res->execute();
$debug.="cookie right selector<br>cookie wrong token (all DB entry for that user are deleted)<br>";
}
} else {
$debug.="selector not found in DB<br>";
}
} else {
$debug.="skip the cookie check: ";
if (!empty($_SESSION['user'])) $debug.="session already set<br>";
if (empty($_COOKIE['remember'])) $debug.="no cookie set<br>";
}
?>
if(isset($_SESSION['last_action'])){
$secondsInactive = time() - $_SESSION['last_action'];
$expireAfterSeconds = $expireAfter * 60;
$debug.="last action: $secondsInactive seconds ago<br>";
if($secondsInactive >= $expireAfterSeconds){
//User has been inactive for too long.
//Kill their session.
session_unset();
session_destroy();
$debug.="session destroy for inactivity<br>";
}
}
...
session_start();
$_SESSION['user'] = $session_data;
...