检查用户会话和cookie

时间:2014-01-08 15:39:27

标签: php session cookies pdo

我正在尝试检查用户的会话是否可用且cookie是否可用。因此,如果用户没有会话,请检查cookie是否存在。如果它们是可用的cookie,则重置会话。

当我第一次登录时,它正在设置会话和cookie,但是当我关闭浏览器并再次尝试时,即时退出。我知道发生了什么,它不是出于某种原因在loginwithcookie中设置会话。我做错了什么

这是登录类的一部分

public function __construct(DB $pdo)
{
    $this->pdo = $pdo->pdo;

    if(isset($_GET['logout'])){
        $_SESSION = array();
        session_destroy();
        setcookie('key', $cookieki, time()-3600, '/ff', 'www.dldesigns.me');

        header('Location: index');
    }

    if(!empty($_SESSION['user_sess']) && $_SESSION['logged_in'] === true){
        // check sessions
        $this->loginwithsessions();
    } else if(isset($_COOKIE['key'])) {
        $this->loginwithcookie();
    }

}

public function loginwithsessions()
{
    $query = $this->pdo->prepare('SELECT * FROM `users` WHERE `user_key` = ?');

    $query->bindValue(1, $_SESSION['user_sess']);

    $query->execute();

    $result = $query->fetchAll();

    if(count($result) == 1){
        // session matches database
        $this->user_logged_in = true;
    }
}

public function loginwithcookie()
{
    $query = $this->pdo->prepare('SELECT * FROM `users` WHERE `cookie_key` = ?');

    $query->bindValue(1, $_COOKIE['key']);

    $query->execute();

    $result = $query->fetchAll();
    $fetch = $query->fetch();

    if(count($result) == 1){
        // cookie matches database
        $this->user_logged_in = true;
        $_SESSION['user_sess'] = $fetch['user_key'];
        $_SESSION['logged_in'] = true;
    }
}

public function checklogin()
{
    if(!empty($_SESSION['user_sess']) && ($_SESSION['logged_in'] === true) && (!empty($_COOKIE['key'])) && $this->user_logged_in === true){
        return true;
    } else {
        return false;
    }
}

public function loginwithdata($email, $password)
{
    $query = $this->pdo->prepare('SELECT * FROM `users` WHERE `email` = ?');

    $query->bindValue(1, $email);

    try{

    $query->execute();

    $data = $query->fetch();

    $salt = $data['salt'];
    $userkey = $data['user_key'];
    $hashed_pass = sha1(md5($salt.$password));

    if($this->verify($hashed_pass, $email) === true){

        $_SESSION['user_sess'] = $userkey;
        $_SESSION['logged_in'] = true;
        $this->user_logged_in = true;

        $cookieki = sha1(uniqid(mt_rand(), true));

        setcookie('key', $cookieki, time()+3600, '/ff', 'www.dldesigns.me');

        $update = $this->pdo->prepare('UPDATE `users` SET `cookie_key` = ? WHERE `user_key` = ?');

        $update->bindValue(1, $cookieki);
        $update->bindValue(2, $userkey);

        $update->execute();
        return true;
    } else {
        return false;
    }

    } catch(PDOException $e) {
        die($e->getMessage());
    }
}

以下是我的检查方式

if($login->checklogin() === true){

echo 'user session is' . $_SESSION['user_sess'];
echo '<br />';
echo 'cookie is' . $_COOKIE['key'];

} else {
    echo "not logged in";
}

0 个答案:

没有答案