我有一个使用mercadopago支付的网站(类似于来自南美的PayPal(。
当用户完成付款并被重定向回我的网站时,我会得到一个新的会话id,我无法读取旧的会话id也无法读取以前设置的cookie。
我的问题是,我需要cookie或会话值来保持用户登录,如果没有,我需要再次询问用户和密码,而客户端不喜欢这样。
这是我用来设置cookie的代码,注释解释了我的问题:
<?php
session_start();
include("db-connection.php");
if(isset($_SESSION["id_alumno"]))
{
$sid=session_id();
if(isset($_COOKIE["user_token"])){
//just for debbuging
//echo "user_token is a " . $_COOKIE["user_token"];
}else{
//set cookie and update same value in database
setcookie("user_token", $sid, time()+2*24*60*60);
$id_alumno=$_SESSION["id_alumno"];
$sql="UPDATE `alumno` SET `login_token` = '$sid', `login_creado` = NOW() WHERE `alumno`.`id` = '$id_alumno'";
$res=mysqli_query($link, $sql); //this connection values are send in a db-connection.php already included.
}
}else{
$cookie_value=$_COOKIE["user_token"]; // here is my problem, I can't access this value, checking cookie information using chrome and the plugin web developer, I get 2 PHPSESSID (old which was used to set cookie with user_token, and also the user token value, and also this new PHPSESSID)
if(isset($cookie_value)){
$sql="SELECT * FROM alumno where login_token='$cookie_value' and login_token!='no'";
$res=mysqli_query($link, $sql);
if($reg=mysqli_fetch_array($res))
{
//here I can login back the user
}//mysql query
}//if isset cookie value
}
?>
您正在使用session_start((及其默认选项。一旦您离开网站,会话cookie就会过期。
试试手册中的示例#3:
<?php
// This sends a persistent cookie that lasts a day.
session_start([
'cookie_lifetime' => 86400,
]);
?>
这会发送一个持续一天的持久cookie。
另请参阅:如何在PHP中创建持久会话?