关于ajax的PHP会话

时间:2017-08-10 08:52:03

标签: php ajax session

我为我的ios应用程序构建了一个php后端库,我正在使用会话来了解用户是否已登录。但出于某种原因,即使设置了会话变量,当我尝试检索它时,它被检索为未定义,使我的应用程序认为用户没有登录,即使用户已登录。是否有使用会话的替代方法,或者我设置会话错误?这是代码:

登录电话:

session_start();
// Login stuff
$_SESSION["id"] = /* My id, which isn't undefined */;

检查用户是否已登录:

session_start();
if (isset($_SESSION["id"])) {
    $id = isset($_SESSION["id"]);
    echo $id;
    // do stuff
}
else {
    echo "You are not logged in.";
    // user not logged in
    // This condition is always called, and I am not able to change it no matter what I do.
}

3 个答案:

答案 0 :(得分:1)

编辑:这个答案是指最初发布的代码,后来由OP编辑。

uint transactionFee = (msg.value * 2) / 100; uint transactionReward = (msg.value * 2) / 100; transactionFee = limitTransactionCosts(transactionFee); transactionReward = limitTransactionCosts(transactionReward); uint receiverMoney = msg.value - transactionFee - transactionReward;

应该是

if ($id = $_SESSION["id"]) {

即。 if ($id == $_SESSION["id"]) {不是==

单个等于的值设置为左侧变量,结果(假设实际设置为=始终计算为{ {1}}。如果$_SESSION["id"]为null或未设置,则表达式将始终评估为true

双等于比较两个变量。

但是,更常规的解决方案就是:

$_SESSION["id"]

答案 1 :(得分:1)

Ajax请求不会自己保存会话cookie,您可能想使用JWT令牌

看看这个JWT tutorial

答案 2 :(得分:0)

只做

// On the first page
session_start(); // Login stuff
$user_id = 2; //or something from the database or via authentication.
 $_SESSION["id"] = $user_id;   /* My id, which isn't undefined */;

在目标页面上;

   session_start();
    if(isset($_SESSION["id"])){ 
    $id = $_SESSION["id"];
    echo " session id is set do your processing here.";
    }else{
      echo "session id is not set";
    }