doudiejian5827 2019-05-11 09:03
浏览 128

PHP setcookie工作但不是在所有目录中

I am implementing a 'remmeber me' system in PHP, setting a cookie to keep the user logged in. Here is a snippet of my 'sign in code' :

if(password_verify(trim($_POST['password']), $hash) == false) {
        $incorrect_err = true;
} else {

       // Excellent! All good
       $_SESSION['signed_in'] = true;
       $_SESSION['id'] = $id;
       $_SESSION['username'] = $username;
       $_SESSION['first_name'] = $first_name;
       $_SESSION['last_name'] = $last_name;
       $_SESSION['email'] = $email;
       $_SESSION['hash'] = $hash;
       $_SESSION['profile_picture'] = $profile_picture;

       // Update 'last activity' in database
       $sql = 'UPDATE `users` SET `last_activity` = CURRENT_TIMESTAMP, `times_signed_in` = `times_signed_in` + 1 WHERE `id` = ' . strval($_SESSION['id']);
       mysqli_query($conn, $sql);

        //Set cookie if necessary
        if(!empty($_POST['keep-me-signed-in-input'])) {
             $days = 30;
             $value = $_SESSION['hash'];
             setcookie("rememberme",$value,time()+ ($days * 24 * 60 * 60), '/');
       }


       // Go to correct page
       if(!empty($_SESSION['destination'])) {
       $location = 'location: ' . $_SESSION['destination'];
           header($location);
       } else {
           header('location: dashboard');
       }
}

However, now when I sign in, I am not taken to the dashboard page as expected. Also, it seems the cookie can only be read by pages in the same directory (pages/users/) as the sign in page, even though I put a "/" into my setcookie statement.

This is how my main.php (included at the start of every page load) looks:

if(!($_SESSION['signed_in'] == true)) { // User is logged out

    if(isset($_COOKIE['rememberme']) && $sign_in_from_cookie !== false) {
        $hash = $_COOKIE['rememberme'];
        $sql = 'SELECT * FROM `users` WHERE `id` = "' . $hash . '"';
        if($result = mysqli_query($conn, $sql)) {
            $row = mysqli_fetch_assoc($result);
            $_SESSION['email'] = $row['email'];
            $_SESSION['first_name'] = $row['first_name'];
            $_SESSION['last_name'] = $row['last_name'];
            $_SESSION['signed_in'] = true;
            $_SESSION['hash'] = $hash;
            $_SESSION['username'] = $row['username'];
            $_SESSION['profile_picture'] = $row['profile_picture'];
            $_SESSION['id'] = $row['id'];
        }
    }

}

Does anybody know what in the world I have done wrong?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 c程序不知道为什么得不到结果
    • ¥40 复杂的限制性的商函数处理
    • ¥15 程序不包含适用于入口点的静态Main方法
    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置