如何在 PHP 中使用登录 cookie 连接用户? [英] How to connect user with a login cookie in PHP?

查看:31
本文介绍了如何在 PHP 中使用登录 cookie 连接用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我在本地主机上进行测试.我有这个 index.php 文件,其中包含以下记住我"复选框:

First of all, I am testing on localhost. I have this index.php file which contains the following "remember me" checkbox:

<input type="checkbox" id="login_remember" name="login_remember">

登录表单发布到 loginvalidate.php,其中包含以下 php 脚本.我已经包含了很多注释来简化阅读我的代码的过程.请注意,我很确定下面的所有内容都可以正常工作.

The login form posts to loginvalidate.php, which includes the following php script. I have included a lot of comments to ease the process of reading my code. Note that I'm pretty sure that everything below works fine.

if (isset($_POST['login_submit'])) {  //SETS VARIABLES FROM FORM
$email = $_POST[trim('login_email')];
$password = $_POST['login_password'];
$remember = isset($_POST['login_remember']) ? '1' : '0';

$db_found = mysqli_select_db($db_handle,$sql_database);  //OPENING TABLE

$query = "SELECT password FROM registeredusers WHERE email = '$email'";
$result = mysqli_query($db_handle, $query) or die (mysqli_error($db_handle));

$row = mysqli_fetch_assoc($result);
$numrows = mysqli_num_rows($result);
if ($numrows!=0)  //IF EMAIL IS REGISTERED
{
  if ($row['password'] == $password) {  //IF PASSWORD IN DATABASE == PASSWORD INPUT FROM FORM
        if ($remember == '1'){  //IF USER WANTS TO BE REMEMBERED
        $randomNumber = rand(99,999999);  //RANDOM NUMBER TO SERVE AS A KEY
        $token = dechex(($randomNumber*$randomNumber));  //CONVERT NUMBER TO HEXADECIMAL FORM
        $key = sha1($token . $randomNumber);
        $timeNow = time()*60*60*24*365*30;  //STOCKS 30 YEARS IN THE VAR

         $sql_database = "registeredusers";
         $sql_table = "rememberme";

         $db_found = mysqli_select_db($db_handle,$sql_database);  //OPENING TABLE

         $query_remember = "SELECT email FROM rememberme WHERE email = '$email'";  //IS THE USER IN TABLE ALREADY
         $result = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));

        if (mysqli_num_rows($result) > 0) {  //IF USER IS ALREADY IN THE REMEMBERME TABLE
         $query_update = "UPDATE rememberme SET
         email      = '$email'
         user_token = '$token'
         token_salt = '$randomNumber'
         time       = '$timeNow'";
    }
    else {  //OTHERWISE, INSERT USER IN REMEMBERME TABLE
         $query_insert = "INSERT INTO rememberme
        VALUES( '$email', '$token', '$randomNumber', '$timeNow' )";
    }
  setcookie("rememberme", $email . "," . $key, $timenow);
    }
          header('Location: homepage.php');  //REDIRECTS: SUCCESSFUL LOGIN
        exit();
    }

然后,当我关闭 Internet 浏览器并返回 index.php 时,我希望 cookie 自动连接用户.这是在我的 index.php 中:

Then, when I close the internet browser and come back to index.php, I want the cookie to automatically connect the user. This is in my index.php:

include 'db_connect.php';
    $sql_database = "registeredusers";
    $db_found = mysqli_select_db($db_handle,$sql_database);  //OPENING TABLE
    session_start();
    if (isset($_COOKIE['rememberme'])) {
        $rememberme = explode(",", $_COOKIE["rememberme"]);
        $cookie_email = $rememberme[0];
        $cookie_key = $rememberme[1];

        $query_remember = "SELECT * FROM rememberme WHERE email = '$cookie_email'";  //IS THE USER IN TABLE ALREADY
        $result_remember = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));

        $row = mysqli_fetch_assoc($result_remember);
            $token = $row['user_token'];
            $randomNumber = $row['token_salt'];
        $key = sha1($token . $randomNumber);  //ENCRYPT TOKEN USING SHA1 AND THE RANDOMNUMBER AS SALT

        if ($key == $cookie_key){
            echo "lol";
        }
    }

问题是,它从不回显lol".另外,有没有人对我如何连接用户有任何见解?又名,这些行内应该写什么:

The problem is, it never echoes "lol". Also, does anyone have any insight on how I could connect the users? AKA, what should go inside these lines:

if ($key == $cookie_key){
            echo "lol";
        }

谢谢!我还是 PHP 和 SQL 的新手,所以如果我犯了一些初学者错误,请多多包涵.

Thank you! I'm still new to PHP and SQL so please bear with me if I have made some beginner errors.

编辑!:在反复查看我的代码后,我认为我的错误可能出在这些行中.我不确定语法,以及我用来将值存储到 $token 和 $randomNumber 中的方法:

EDIT!: After looking again and again at my code, I think that my error might lie in these lines. I'm not sure about the syntax, and the method I am using to store values into $token and $randomNumber:

$query_remember = "SELECT * FROM rememberme WHERE email = '$cookie_email'";  //IS THE USER IN TABLE ALREADY
    $result_remember = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));

    $row = mysqli_fetch_assoc($result_remember);
        $token = $row['user_token'];
        $randomNumber = $row['token_salt'];

推荐答案

PHP 中的登录脚本可以使用 会话.

A login script in PHP can be implemented using sessions.

简单来说,会话​​是唯一的,并且只要页面打开(或直到它超时)就一直存在.如果您的浏览器已关闭,会话也会发生同样的情况.

Making it simple, sessions are unique and lives as long as the page is open (or until it timeouts). If your browser is closed, the same happens to the session.

它们实施起来非常简单.首先,确保在每个页面的开头开始会话:

They are pretty simple to implement. First, make sure you start sessions at the beginning of each page:

<?php session_start(); ?>

注意:此调用出现在任何页面输出之前很重要,否则会导致标题已发送"错误.

Note: It's important that this call comes before of any page output, or it will result in an "headers already sent" error.

好的,现在您的会话已启动并正在运行.接下来做什么?这很简单:用户通过登录表单发送其登录名/密码,然后您对其进行验证.如果登录有效,则将其存储到会话中:

Alright, now your session is up and running. What to do next? It's quite simple: user sends it's login/password through login form, and you validate it. If the login is valid, store it to the session:

if($validLoginCredentials){
    $_SESSION['user_id'] = $id;
    $_SESSION['user_login'] = $login;
    $_SESSION['user_name'] = $name;
}

或作为数组(我更喜欢):

or as an array (which I prefer):

if($validLoginCredentials){
    $_SESSION['user'] = array(
        'name' => $name,
        'login' => 'login',
        'whichever_more' => $informationYouNeedToStore
    );
}

好的,现在你的用户已经登录了.那么你怎么知道/检查呢?只需检查用户的会话是否存在.

Ok, now your user is logged in. So how can you know/check that? Just check if the session of an user exists.

if(isset($_SESSION['user_id'])){ // OR isset($_SESSION['user']), if array
// Logged In
}else{
// Not logged in :(
}

当然你可以更进一步,除了检查会话是否存在,在数据库中搜索会话存储的用户 ID 来验证用户.这完全取决于您需要多少安全性.

Of course you could go further, and besides of checking if the session exists, search for the session-stored user ID in the database to validate the user. It all depends on the how much security you need.

在最简单的应用程序中,永远不会存在 $_SESSION['user'] 除非您在登录操作中手动设置它.因此,只需检查它是否存在即可告诉您用户是否已登录.

In the simplest application, there will never exist a $_SESSION['user'] unless you set it manually in the login action. So, simply checking for it's existence tells you whether the user is logged in or not.

注销:只需销毁它.你可以使用

Loggin out: just destroy it. You could use

session_destroy();

但请记住,这会破坏您为该用户设置的所有会话.如果您还使用了 $_SESSION['foo'] 和 $_SESSION['bar'],它们也会消失.在这种情况下,只需取消设置特定会话:

But keep in mind that this will destroy all sessions you have set up for that user. If you also used $_SESSION['foo'] and $_SESSION['bar'], those will be gone as well. In this case, just unset the specific session:

unset($_SESSION['user']);

大功告成!用户不再登录!:)

And done! User is not logged in anymore! :)

嗯,就是这样.再次提醒您,这些是非常简单的登录方法示例.您需要多研究一点,并根据应用程序的安全要求,通过更多层的安全检查来改进代码.

Well, that's it. To remind you again, these are very simple login methods examples. You'll need to study a bit more and improve your code with some more layers of security checks depending on the security requirements of your application.

这篇关于如何在 PHP 中使用登录 cookie 连接用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆