dongliuliu0385 2018-06-11 21:39
浏览 71

用cookie存储用户ID的用户ID和没有会话(记住我)

I have read a ton of question about it and the discussions are different along with the answers on this matter.

I need to have the User ID in order to retrieve his data from the DB and create a session with this data in order to create a continues login.

Hashing the session:

function createNewUserSession($uid, $email, $salt){
    $session_key = $email.$salt;
    $options = [
        'cost' => 11
    ];
    $session_key = password_hash($session_key, PASSWORD_BCRYPT, $options);
    $connect = mysqliConnect();

    $query = "UPDATE `users` SET";
    $query .= " session_key = '$session_key'";
    $query .= " WHERE id = '$uid'";
    mysqli_query($connect, $query);

    return $session_key;
}

function generateRandomString($length) {
        return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+|"}?><~', ceil($length/strlen($x)) )),1,$length);
}

    $user_session_salt = generateRandomString(32);

    if (isset($_COOKIE['sk'])) {
        if (password_verify($email.$_COOKIE['sk'], $session_key)) {
        // Creating Sessions
        $_SESSION['uid'] = $uid;
        $_SESSION['fName'] = $fName;
        $_SESSION['lName'] = $lName;
        } else {
            // Creating New Sessions
            createNewUserSession($uid, $email, $user_session_salt);
            $_SESSION['uid'] = $uid;
            $_SESSION['fName'] = $fName;
            $_SESSION['lName'] = $lName;

            // Creating Cookies
            setcookie("sk", $user_session_salt, time() + (90 * 24 * 60 * 60), '/', '.mywebsite.io');
        }
    }

Renew Session:

function restoreSession($uid) {
    $connect = mysqliConnect();

    $query = "SELECT * FROM `users` WHERE id = '$uid'";
    $result = mysqli_query($connect, $query);

    if (mysqli_num_rows($result) == 1) {
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        $uid = $row['id'];
        $email = $row['email'];
        $fName = $row['first_name'];
        $lName = $row['last_name'];
        $session_key = $row['session_key'];

        if (isset($_COOKIE['sk']) && !isset($_SESSION['uid'])) {

            $user_salt = $_COOKIE['sk'];

            if (password_verify($email.$user_salt, $session_key)) {
                // Creating Sessions
                $_SESSION['uid'] = $uid;
                $_SESSION['fName'] = $fName;
                $_SESSION['lName'] = $lName;
            }
        }
    }
}

I know this is not perfect, but I'm still learning and need some adequate input on this matter.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统