简体   繁体   English

使用cookie登录php

[英]Using cookies for login php

I have an in-campus trading web site. 我有一个校园内交易网站。 The site is using sessions for login system. 该站点正在使用会话进行登录系统。 I wanted to add cookies to login system. 我想向登录系统添加cookie。 However, since I have never used php cookies, for some reason system does not work. 但是,由于我从未使用过PHP cookie,因此由于某些原因系统无法正常工作。 Actually without remembering (with using sessions) system works fine but it does not work with cookies. 实际上,无需记住(使用会话)系统可以正常工作,但不适用于Cookie。

Here my class before incrementing: 在增加之前,这里是我的课:

class LoggedUser{
public static function GetUserId(){
    return $_SESSION['LoggedUser']['Id'];
}
public static function GetUserEmail(){
    return $_SESSION['LoggedUser']['Email'];
}
public static function LogInUser(
        $user_id,
        $user_email,
    ){
        $_SESSION['LoggedUser'] = array();
        $_SESSION['LoggedUser']['Id'] = $user_id;
        $_SESSION['LoggedUser']['Email'] = $user_email;

}
public static function IsUserLogged(){
    $result = false;
    if(isset($_SESSION['LoggedUser']))
        $result = true;
    return $result;
}
public static function LogOutUser(){
    unset($_SESSION['LoggedUser']);
}

}

After the incrementing: 递增后:

class LoggedUser{
public static function GetUserId(){
    if(isset($_COOKIE['LoggedUserId']))
        return $_COOKIE['LoggedUserId'];
    return $_SESSION['LoggedUser']['Id'];
}
public static function GetUserEmail(){
    if(isset($_COOKIE['LoggedUserId']))
        return $_COOKIE['LoggedUserEmail'];
    return $_SESSION['LoggedUser']['Email'];
}
public static function LogInUser(
        $user_id,
        $user_email,
        $remember
    ){
    if($remember == true){
        setcookie("LoggedUserId", $user_id, time()+60*60*24*30);
        setcookie("LoggedUserEmail", $user_email, time()+60*60*24*30);
    }
    else{
        $_SESSION['LoggedUser'] = array();
        $_SESSION['LoggedUser']['Id'] = $user_id;
        $_SESSION['LoggedUser']['Email'] = $user_email;
    }
}
public static function IsUserLogged(){
    $result = false;
    if(isset($_COOKIE['LoggedUserId']))
        $result = true;
    if(isset($_SESSION['LoggedUser']))
        $result = true;
    return $result;
}
public static function LogOutUser(){
    unset($_COOKIE['LoggedUserId']);
    unset($_COOKIE['LoggedUserEmail']);
    unset($_SESSION['LoggedUser']);
}

}

Do you have any idea why system does not work with cookies? 您是否知道为什么系统无法使用Cookie?

Is the login PHP file in a sub-directory? 登录PHP文件位于子目录中吗?

If so, add a starting directory in the set cookie command 如果是这样,请在set cookie命令中添加一个起始目录

setcookie("LoggedUserId", $user_id, time()+60*60*24*30, "/"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM