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

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

问题描述

首先,我在localhost上测试。我有这个index.php文件,其中包含以下记住我复选框:

 < input type =checkboxid =login_remembername =login_remember> 

登录表单发送到loginvalidate.php,其中包括以下php脚本。我已经包括了很多意见,以缓解读取我的代码的过程。注意,我非常确定下面的一切都很好。

  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)或die(mysqli_error($ db_handle));

$ row = mysqli_fetch_assoc($ result);
$ numrows = mysqli_num_rows($ result);
if($ numrows!= 0)//如果电子邮件已注册
{
if($ row ['password'] == $ password){//如果PASSWORD IN DATABASE == PASSWORD INPUT FROM FORM
if($ remember =='1'){//如果用户想要记住
$ 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'; //是用户在表ALREADY
$ result = mysqli_query($ db_handle,$ query_remember)或die(mysqli_error($ db_handle));

if(mysqli_num_rows($ result)> 0){//如果用户已在REMEMBERME表中存在
$ query_update =UPDATE rememberme SET
email ='$ email '
user_token ='$ token'
token_salt ='$ randomNumber'
time ='$ timeNow';
}
else {//其他,在REMEMBERME表中插入用户
$ query_insert =INSERT INTO rememberme
VALUES('$ email','$ token','$ randomNumber ','$ timeNow');
}
setcookie(rememberme,$ email。,。$ key,$ timenow);
}
header('Location:homepage.php'); // REDIRECTS:SUCCESSFUL LOGIN
exit();
}

然后,当我关闭互联网浏览器并返回index.php,我想让cookie自动连接用户。这在我的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'; //是用户在表ALREADY
$ result_remember = mysqli_query($ db_handle,$ query_remember)或死(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){
echolol;
}
}

问题是,它从来不回应lol。此外,有谁有任何洞察如何我可以连接用户? AKA,应该在这些行内:

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

谢谢!我仍然是新的PHP和SQL,所以如果我有一些初学者的错误,请忍受。



编辑!:再次看到我的代码,我认为我的错误可能在这些行。我不确定的语法,我使用的方法来存储值到$ token和$ randomNumber:

  $ query_remember =SELECT * FROM rememberme WHERE email ='$ cookie_email'; //是用户在表ALREADY 
$ result_remember = mysqli_query($ db_handle,$ query_remember)或死(mysqli_error($ db_handle));

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


解决方案

在PHP中:


  1. 使用会话

  2. 使用 Cookie

我会尝试在下面的原始表单中解释这两种用法,



使用会话



简单来说,会话​​是独一无二的,只要页面打开(或直到它超时)。如果您的浏览器关闭,会话也会发生同样的情况。



如何使用?



相当简单的实现。首先,请确保您在每个网页的开头开始会话:

 <?php session_start ?> 

注意:此调用在 strong>,否则将导致已发送标头错误。

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

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

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

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

好,现在您的用户已登录。那?只需检查用户会话是否存在。

  if(isset($ _ SESSION ['user_id' OR isset($ _ SESSION ['user']),如果数组
//登录
} else {
//未登录:(
}

当然,您可以进一步,除了检查会话是否存在,搜索会话存储的用户ID



在最简单的应用程序中,永远不会存在$ _SESSION ['user'],除非你在登录操作中手动设置它,所以,只需检查它的存在就告诉你用户是否登录。



登录:可以使用

  session_destroy(); 

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

  unset($ _ SESSION [ '用户']); 

完成!用户不再登录! :)



使用Cookie



Cookie除了 >在客户端浏览器,并持续只要你告诉他们。例如,当您将其设置为在 $ timeNow 时失效,您正在使用Cookie作为会话。



我通常不喜欢使用Cookie进行简单登录,因为它们需要更高级的安全检查。由于他们存储在用户的浏览器,他们可以很容易地被操纵,恶意用户可以生成假登录信息和登录您的系统。



如何使用它?



与会议一样。区别在于设置/取消设置Cookie:

  //设置Cookie 
//您可以使用数组在一个cookie中存储多个用户信息
$ user = array(
'id'=> $ id,
'name'=> $ name,
'login '=> $ login,

setcookie(loginCredentials,$ user,time()* 7200); //在2小时后过期

//现在注销,只要将cookie设置为空白并已过期
setcookie(loginCredentials,,time() - 3600) ; //Expires1小时前

要检查用户是否登录,但是使用不同的变量:$ _COOKIE

  if(isset($ _ COOKIE ['user'] ['id']&&!empty(isset($ _ COOKIE ['user'] ['id'])){
//登入
} else {
/ /未登录:(
}

这些是非常简单的 登录方法示例。您需要更多地了解这两种方法,并根据安全要求,使用一些更多的安全检查来改进代码的申请。


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">

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();
    }

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";
        }
    }

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";
        }

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

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'];

解决方案

There are basically two ways you can implement a login script in PHP:

  1. Using Sessions
  2. Using Cookies

I'll try to explain both uses in a raw form below, so keep in mind there is a lot more to know about each of them.

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.

How to use it?

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 :(
}

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.

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();

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! :)

Using Cookies

Cookies works somewhat alike sessions, except they are stored in the client browser and lasts as long as you tell them to. For instance, you were using cookies "as sessions" when you were setting them to expire at $timeNow.

I usually don't like using cookies for simple logins as they require more advanced security checks. Since they are stored at users' browser, they can easily be manipulated and malicious users could generate false login information and log into your system.

How to use it?

Pretty much as you do with sessions. The difference is about setting/unsetting the cookie:

// To set a Cookie
// You could use the array to store several user info in one cookie
$user = array(
    'id' => $id,
    'name' => $name,
    'login' => $login,
)
setcookie("loginCredentials", $user, time() * 7200); // Expiring after 2 hours

// Now to log off, just set the cookie to blank and as already expired
setcookie("loginCredentials", "", time() - 3600); // "Expires" 1 hour ago

To check if a user is logged in, you can use the same example as of the session, but using a different variable: $_COOKIE

if(isset($_COOKIE['user']['id'] && !empty(isset($_COOKIE['user']['id']))){
// Logged In
}else{
// Not logged in :(
}

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

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

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