duandian8251 2015-12-14 18:34
浏览 34

如何让用户登录php中的会话和cookie,缩短

I originally made a post that I think was too long and people did not want to read everything. So I have done some debugging to make it easier to help. Okay so the problem is that I want a user to stay logged in if they select the remember me checkbox. When they check it, it will create a cookie and insert that cookie hash into a db table names session. Then it will run a function if the user closes out his/her browser and see if they still have the cookie.

If the cookie exists then it should pull in the cookie hash match the id from session table to the id in the user table and log that user in.

So what I have working is everything except for when the user joins back it is not pulling data through. I will show relevant code to makes since. If you have any comments or ideas please post.

I tried to make this as short as I could and give you the relevant information to help me out. If this does not seem enough you can check my original post for more information: Session is not setting after the user has hit remember me checkbox

Here is where I check to see if a user cookie already exists and if it does to log them in:

<?php
session_start();
$GLOBALS['config'] = array(
  'mysql' => array(
    'host' =>  '127.0.0.1',
    'username' => 'root',
    'password' => 'root',
    'db' => 'register_login'
  ),
  'remember' => array(
    'cookie_name' => 'hash',
    'cookie_expiry' => 604800
  ),
  'session' => array(
    'session_name' => 'user',
    'token_name' => 'token'
  )
);

spl_autoload_register(function($class) {
  require_once 'classes/' . $class . '.php';
});

require_once 'functions/sanitize.php';

if(Cookie::exists(Config::get('remember/cookie_name')) && !Session::exists(Config::get('session/session_name'))) {
  $hash = Cookie::get(Config::get('remember/cookie_name'));
  $hashCheck = DB::getInstance()->get('users_session', array('hash', '=', $hash));

  if($hashCheck->count()) {
    $user = new User($hashCheck->first()->user_id);
    $user->login();
  }
}
 ?>

In the User.php class file here is the relevant code: In this class the PROBLEM is that under the login method $this->exists() is returning false. I echo'd it out and print_r and it is not returning any data from the init.php file.

<?php

class User {
  private $_db,
          $_data,
          $_sessionName,
          $_cookieName,
          $_isLoggedIn;

  public function __construct($user = null){
    $this->_db = DB::getInstance();

    $this->_sessionName = Config::get('session/session_name');
    $this->_cookieName = Config::get('remember/cookie_name');


    if(!$user){
      if(Session::exists($this->_sessionName)) {
        $user = Session::get($this->_sessionName);

          if($this->find($user)) {
            $this->_isLoggedIn = true;
          } else {

          }
        } else {
        $this->find($user);
      }
    }
  }


 public function find($user = null) {
    if($user){
      $field = (is_numeric($user)) ? 'id' : 'username';
      $data = $this->_db->get('users', array($field, '=', $user));

      if($data->count()) {
        $this->_data = $data->first();
        return true;
      }
    }
    return false;
  }

public function login($username = null, $password = null, $remember = false) {
    if(!$username && !$password && $this->exists()) {
      echo 'Ok';
      //Session::put($this->_sessionName, $this->data()->id);
    } else {
      echo 'no ok';
      $user = $this->find($username);
      if($user){
        if($this->data()->password === Hash::make($password, $this->data()->salt)) {
          Session::put($this->_sessionName, $this->data()->id);

          if($remember){
            $hash = Hash::unique();
            $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

            if(!$hashCheck->count()) {
              $this->_db->insert('users_session',array(
                'user_id' => $this->data()->id,
                'hash' => $hash
              ));
            } else {
              $hash = $hashCheck->first()->hash;
            }

            Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
          }
          return true;
        }
      }
    }
    return false;
  }

  public function exists() {
    return (!empty($this->_data)) ? true : false;
  }

Here is the login.php form: It just has a form at the bottom and at the top is where I have some validation(dont worry about that), Where I have remember variable is where we check to see if the user checked the box to run the code in User class to create the cookie.

<?php
require_once 'core/init.php';
if(Input::exists()) {
  if(Token::check(Input::get('token'))) {

      $validate = new Validate();
      $validation = $validate->check($_POST,array(
          'username' => array('required' => true),
          'password' => array('required' => true)
      ));

      if($validation->passed()) {
        $user = new User();

        $remember = (Input::get('remember') === 'on') ? true : false;
        $login = $user->login(Input::get('username'), Input::get('password'), $remember);

        if($login) {
          Redirect::to('index.php');
        } else {
          echo '<p>Sorry, logging in failed</p>';
        }
      } else {
        foreach($validation->errors() as $error) {
          echo $error, '<br>';
        }
      }
  }
}
?>

<form action="" method="post">
  <div class="field">
    <label for="username">Username</label>
    <input type="text" name="username" id="username" autocomplete="off">
  </div>

  <div class="field">
    <label for="password">Password</label>
    <input type="password" name="password" id="password" autocomplete="off">
  </div>

  <div class="field">
    <label for="remember">
      <input type="checkbox" name="remember" id="remember">Remember Me
    </label>
  </div>

  <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
  <input type="submit" value="Log In">
</form>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 关于大棚监测的pcb板设计
    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题
    • ¥20 win11修改中文用户名路径
    • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入