PHP开发之ThinkPHP实现自动登录功能(简单易懂)

浏览:11879 发布日期:2016/09/13 分类:技术分享 关键字: Thinkphp,自动登录
通常,我们在很多网站里面都可能看得到 有一个复选框 提示一个 7天内自动登录(或者其它的内容)。那么这个功能该如何去简单的实现呢。接下来,我给大家简单说说!

大概的实现思路呢,是这样的,首先我们判断用户是否有登录,然后我们先从SESSION里面读取,如果SESSION没有的话呢。我们就去COOKIE里面读取。
代码:

Login.html<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>登录</title>
</head>
<body>
    <form action="{:U('Login/DoLogin')}" method="post">
        username <input type="text" name="username" />

        password <input type="password" name="password" />

        remember <input type="checkbox" name="check" value="1" />

        <input type="submit" value="Login" />
    </form>
</body>
</html>


LoginController.class.php  //这里直接用模拟的,不查询数据了。

 public function DoLogin()
 {

$Key="phpsafe";
session_start();
if($_POST['username'] == 'phpsafe' && $_POST['password'] == '123456'){
    //登录成功
    $User['id']            = 1;        //用户id
    $User['name']          = 'phsafe.com';    //用户显示名称
    $_SESSION['UserInfo']  = $User;
    //如果选中记住我,就将登录信息放入Cookie中
    if($_POST['check'] == '1'){
        //将登录信息,存放在Cookie中
        $Value = serialize($User);            
        $Str   = md5($value.$Key);
        setcookie('Login', $Str . $Value,time()+60*60*24*30,'/');
    }
    $this->redirect('Index');
}else{
    echo '用户名或密码不匹配';
}

 }
IndexController.class.php   public function Index()
   {
       $Key="phpsafe";
//开启Session
session_start();
//如果Session中没有登录信息,尝试从Cookie中加载用户信息
if (empty($_SESSION['UserInfo']['id'])) {
    $Value       =$_COOKIE['Login'];
    // 去掉魔术引号
    if (get_magic_quotes_gpc()) {
        $Value = stripslashes($Value);
    }
    $Str        = substr($Value,0,32);
    $Value        = substr($Value,32);
    //校验
    if (md5($Value . $Key) == $Str) {
        $User                   = unserialize($Value);
        
        $_SESSION['UserInfo'] = $User;
    }
}

   }
就这样 一个简单的自动登录就实现了。是不是易懂呢?

复制或转载请注明出处,文本出自Poacher'Blog:http://www.phpsafe.com/post-17.html
最佳答案
评论( 相关
后面还有条评论,点击查看>>