ThinkPHP3.2.2 method to implement persistent login (remember me) _php instance

Source: Internet
Author: User
Tags auth md5 php programming php template rand setcookie smarty template

The example in this article describes how ThinkPHP3.2.2 implements persistent login functionality. Share to everyone for your reference, specific as follows:

Implement persistent logins, that is, when the user is logged in, check "Remember Me", regardless of whether or not to close the browser, as long as you do not quit the login, in a specified period of time to remain logged in (the disadvantage is on another computer after the login, the previous computer can not continue to remain logged on).

First, a persistent login is implemented using a cookie, but the cookie cannot hold such important information as the user's password, even if it has been encrypted. The solution is to create a new 3 field in the user Login table identifier: Second identity, token: Permanent login ID, timeout: Permanent login timeout.

+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| uid | int (11) | NO | PRI | NULL | auto_increment |
| uname | varchar (20) | YES | | NULL | | |
Upwd | varchar (20) | YES | | NULL | | |
Uflag | Int (11) | YES | | NULL | | |
identifier | varchar (32) | YES | | NULL | | |
Token | varchar (32) | YES | | NULL | | |
Timeout | Int (11) | YES | | NULL | |
+------------+-------------+------+-----+---------+----------------+

When the user registers "Remember Me" login, you should generate a unique identifier, a unique token, and set an expiration time timeout, write the two representative values to the cookie, and set the cookie expiration to timeout. For example: Setcookie (' auth ', "$identifier: $token", $timeout); At the same time, three values are inserted into the data table, when the user once again visit the site, first judge whether the cookie contains auth, if it contains, then go to the database for identity (identifier and token), compared to the success, the user information to write session, The user remains logged on at the same time.

Code:

Controller TestController.class.php

<?php namespace Test\controller;
Use Think\controller;
  Class TestController extends Controller {public Function login () {//To determine whether to log on permanently $this->checklong ();
  Is logged in to the personal Center if (isset ($_session[' username ')) {$this->redirect (' Test/ucenter ');
   }else{//To determine whether there is a COOKIE if (isset ($_cookie[' username ')) {$this->assign (' username ', $_cookie[' username '));
  ///Show Registration page $this->display ("test");
  }///Show Authentication code public Function verifyimg () {$verify = new \think\verify (); $verify->usezh = true; 
  Use the Chinese verification code $verify->length = 4;
 $verify->entry ();
  //Verify logon Public function check () {$verify = new \think\verify ();
   if ($verify->check ("Yzm")) {//judge username password $user = new \test\model\testmodel ();
   $res = $user->checkname (I ("username"), I ("pwd"));
   if ($res = = False) {echo "User name or password error";
    }else{//user information stored in session session ("username", $res [' uname ']);
    Session ("id", $res [' uid ']);
   If the user has checked "Remember Me", keep the persistent login if (I ("Remember")) {  $salt = $this->random_str (16);
     Second part identification $identifier = MD5 ($salt. MD5 (I ("username"). $salt));
     Permanent login Identification $token = MD5 (Uniqid (rand (), true);
     Permanent login timeout (1 weeks) $timeout = time () +3600*24*7;
     Deposit Cookie Setcookie (' auth ', "$identifier: $token", $timeout);
    $user->saveremember ($res [' uid '], $identifier, $token, $timeout);
    ///Put the username in the cookie and save the username information in the form after exiting the login Setcookie (' username ', I (' username '), time () +3600*24);
   Jump to the Member Center $this->redirect (' Test/ucenter ');
  }else{echo "input error";
  }///test STRSTR functions Public Function strstrtest () {$param = "think\verify";
  The third argument is true and returns ' I '; no third argument, return ' \verify ' $name = strstr ($param, ' \ \ ', true);
 Echo $name;
  //User Center Public Function ucenter () {//Determine whether to log on permanently $this->checklong ();
  $this->assign ("session", $_session);
 $this->display ("Ucenter");
  //Exit Login Public Function Loginout () {session (NULL);
  Setcookie (' auth ', ', ', Time ()-1);
 $this->redirect ("Test/login"); }//LiveA random number that is used to generate the salt public Function random_str ($length) {//Generate an array containing uppercase letters, lowercase letters, numbers $arr = array_merge (range (0, 9), RA
  Nge (' A ', ' Z '), Range (' A ', ' Z '));
  $str = ';
  $arr _len = count ($arr);
   for ($i = 0; $i < $length; $i + +) {$rand = Mt_rand (0, $arr _len-1);
  $str. = $arr [$rand];
 return $str;
  //Determine if the persistent logon public function Checklong () {$check = new \test\model\testmodel ();
  $is _long = $check->checkremember ();
   if ($is _long = False) {}else{session ("username", $is _long[' uname '));
  Session ("id", $is _long[' uid '));

 }
 }
}

model TestModel.class.php

<?php namespace Test\model;
Use Think\model;
  Class Testmodel extends model{//Authentication login Information Public function checkname ($name, $pwd) {$admin = M ("admin");
  $info = $admin->getbyuname ($name);
   if ($info!= null) {//Verify password if ($info [' upwd '] = = $pwd) {return $info;
   }else{return false;
  }}else{return false;
  }//When user tick "Remember Me" public function Saveremember ($uid, $identifier, $token, $timeout) {$admin = M ("admin");
  $data [' identifier '] = $identifier;
  $data [' token '] = $token;
  $data [' timeout '] = $timeout;
  $where = "UID =". $uid;
  $res = $admin->data ($data)->where ($where)->save ();
 return $res;
  //Verify that the user is permanently logged in (remember me) public function Checkremember () {$arr = array ();
  $now = time ();
  List ($identifier, $token) = Explode (': ', $_cookie[' auth '));
   if (Ctype_alnum ($identifier) && ctype_alnum ($token)) {$arr [' identifier '] = $identifier;
  $arr [' token '] = $token;
  }else{return false;
  } $admin = M ("admin"); $info = $admin->getbyideNtifier ($arr [' identifier ']);
   if ($info!= null) {if ($arr [' token ']!= $info [' token ']) {return false;
   }else if ($now > $info [' Timeout ']) {return false;
   }else{return $info;
  }}else{return false;

 }
 }
}

View Login Page test.html

<doctype html>
 
 

Attached: module catalogue

Add: Small knitting here recommend a site for the layout of the PHP format landscaping tools to help you in the future of PHP programming code layout:

PHP Code online Format Landscaping tool:Http://tools.jb51.net/code/phpformat

More interested in thinkphp related content readers can view the site topics: "thinkphp Introductory Course", "thinkphp Common Methods Summary", "Smarty Template Primer" and "PHP template technology Summary."

I hope this article will help you with the PHP program design based on thinkphp framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.