没有不值得去解决的问题,也没有不值得去学习的技术!

Implementing Auto-Login for Two Weeks With ThinkPHP 3.2 After Session Initialization

If auto-login is checked, set COOKIE['autologin']
Auto-login within two weeks interface
Auto-login within two weeks interface

Because the session has already started automatically, session initialization settings can no longer be applied. This means that ini_set(‘session.gc_maxlifetime’,   $name[‘expire’]);ini_set(‘session.cookie_lifetime’,  $name[‘expire’]); both fail to take effect, so it is basically certain that the session approach cannot be resolved for now.

I had to turn to cookies to implement this. Although this introduces certain security concerns, it necessitates encrypting the cookie to implement the auto-login feature:

// If auto-login is checked, set COOKIE[‘autologin’]
if(I(‘post.autologin’) == 1) {
//$expire = 1209600; // Save for two weeks
$autologin = serialize(array(‘uid’ => $uid, ‘last_login_time’ => time(), ‘last_login_ip’   => get_client_ip(1)));
cookie(‘autologin’, think_encrypt($autologin), 1209600);
}

If auto-login is checked, set COOKIE['autologin']
If auto-login is checked, set COOKIE[‘autologin’]

think_encrypt is the encryption function. When the user has logged out of the application but COOKIE[‘autologin’] still exists, the following is required:

/* Auto-login within two weeks */
if(!is_login() && cookie(‘autologin’)) {
$autologin = unserialize(think_decrypt(cookie(‘autologin’)));
if (is_array($autologin) && $autologin[‘last_login_ip’] == get_client_ip(1)) {
/* Log in user */
$Member = D(‘Member’);
$Member->login($autologin[‘uid’]);
}
}

Here, think_encrypt and think_decrypt are the encryption and decryption functions, respectively.

The basic logic is roughly as described above.

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系