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

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

问题描述

首先,我正在本地测试。我有这个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)or die(mysqli_error($ db_handle));

$ row = mysqli_fetch_assoc($ result);
$ numrows = mysqli_num_rows($ result);
if($ numrows!= 0)//如果EMAIL被注册
{
if($ row ['password'] == $ password){//如果密码在DATABASE == PASSWORD INPUT FROM FORM
if($ remember =='1'){//如果用户想要记住
$ randomNumber = rand(99,999999); //随机数作为键
$ token = dechex(($ randomNumber * $ randomNumber)); // CONVERT NUMBER TO HEXADECIMAL FORM
$ key = sha1($ token。$ randomNumber);
$ timeNow = time()* 60 * 60 * 24 * 365 * 30; // STOCKS 30年在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'; //是TABLE ALREADY中的用户
$ result = mysqli_query($ db_handle,$ query_remember)或者死(mysqli_error($ db_handle));

if(mysqli_num_rows($ result)> 0){//如果用户在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();
}

然后,当我关闭互联网浏览器并返回到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'; //是TABLE 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); //加密使用SHA1和RANDOMNUMBER作为$

如果($ key == $ cookie_key){
echolol;
}
}

问题是,它永远不会回应哈哈。此外,有没有人有任何见解如何连接用户? AKA,这些行应该怎么做:

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

谢谢!我仍然是PHP和SQL的新手,所以如果我犯了一些初学者错误,请与我联系。



编辑:在一次又一次地看到我的代码之后,我认为我的错误可能在于这些行。我不确定语法,我使用的方法是将值存储到$ token和$ randomNumber中:

  $ query_remember =SELECT * FROM rememberme WHERE email ='$ cookie_email'; //是TABLE 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. 使用 Cookies

我将尝试解释在原始



使用会话



简单,会话是独一无二的,只要页面打开(或直到超时)就可以生活。如果您的浏览器关闭,会话也会发生。



如何使用?



他们是很简单实现。首先,确保您在每个页面开始时开始会话:

 <?php session_start(); ?> 

注意:这个电话来自任何页面输出,否则会导致已发送头文件错误。



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

  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 ['user']) ; 

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



使用Cookie



Cookie的工作方式相似,除了存储在客户端浏览器中,只要你告诉他们,就可以持续。例如,当您设置它们在$ timeNow 时过期时,您正在使用Cookie作为会话。



我通常不喜欢使用cookies进行简单登录,因为它们需要更高级的安全检查。由于它们存储在用户浏览器中,因此可以轻松操作,恶意用户可以生成虚假登录信息并登录到您的系统。



如何使用它?



和会话一样多。不同之处在于设置/取消设置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天全站免登陆