weixin_33674437 2017-08-10 08:52 采纳率: 0%
浏览 29

通过Ajax进行PHP会话

I have built a php backend library, for a ios app of mine, and I am using sessions to know if the user is logged in. But for some reason, even after setting the session variable, when I try to retrieve it, it is retrieved as undefined, making my app think the user isn't logged in, even though the user is logged in. Is there any alternative for using sessions, or did I setup my session wrong? Here is the code:

Login call:

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

Checking whether user is logged in or not:

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.
}
  • 写回答

4条回答 默认 最新

  • ℙℕℤℝ 2017-08-10 08:54
    关注

    EDIT: This answer refers to the code originally posted, which has since been edited by the OP.

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

    should be

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

    i.e. == not =.

    A single equals will set the value of the left-hand variable, and the result, assuming that $_SESSION["id"] is actually set will always evaluate to true . If $_SESSION["id"] is null or not set, then the expression will always evaluate to false.

    A double equals compares the two variables.

    However, a more conventional solution would simply be:

    if (isset($_SESSION["id"])) {
    
    评论

报告相同问题?