6

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

3 回答 3

28

PHP 中的登录脚本可以使用会话来实现。

使用会话

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

如何使用它?

它们很容易实现。首先,确保在每一页的开头开始会话:

<?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']), if array
// Logged In
}else{
// Not logged in :(
}

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

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

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

session_destroy();

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

unset($_SESSION['user']);

并做了!用户不再登录!:)

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

于 2013-09-11T14:15:04.010 回答
6

您的代码不起作用的原因是

  setcookie("rememberme", $email . "," . $key, $timenow); // this is getting expire exactly at same time when it is set

将其替换为

 setcookie("rememberme", $email . "," . $key, time() * 3600);//expire after 1hour 
于 2013-09-11T12:22:45.763 回答
0
time()*60*60*24*365*30

这个时间大于 9999 年,你也不需要设置这个恐怖饼干时间。您设置的 cookie 时间大于 9999 年,并且 php 不允许此配置。在我看来,最好的解决方案是设置新的过期 cookie 时间低于 9999 :))

于 2021-02-28T06:11:28.767 回答