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 树莓派与pix飞控通信
    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题