欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ThinkPHP登录功能的实现方法

程序员文章站 2022-06-22 11:14:18
登陆功能是php程序设计中常见的功能。本文thinkphp实例主要完成注册成功后进入首页,并告诉你是登录用户的功能。具体实现步骤如下: 第一步:在config.php文件...

登陆功能是php程序设计中常见的功能。本文thinkphp实例主要完成注册成功后进入首页,并告诉你是登录用户的功能。具体实现步骤如下:

第一步:在config.php文件中加上:

'user_auth_key'=>'authid'

示例如下:

<?php
if(!defined('think_path')) exit();
return array(
// 定义数据库连接信息
'db_type'=> 'mysql',// 指定数据库是mysql
'db_host'=> 'localhost',
'db_name'=>'myuser', // 数据库名
'db_user'=>'root',
'db_pwd'=>'', //您的数据库连接密码
'db_port'=>'3306',
'db_prefix'=>'think_',//数据表前缀
'user_auth_key'=>'authid'
);
?>

第二步:在adminaction.class.php中的insert()代码中用:

session::set(c('user_auth_key'),$user);

保存登录用户名到session。

完整实现代码如下:

public function insert()
{
header('content-type:text/html; charset=utf-8');//防止出现乱码
$user=$_post['user'];
$this->verifycheck();
$pagemodel = d("user");
$vo = $pagemodel->create(); 
if(false === $vo) die($pagemodel->geterror());
$topicid = $pagemodel->add(); //add方法会返回新添加的记录的主键值
if($topicid)
{
//$_session[c('user_auth_key')]=$user;//不能用此句
session::set(c('user_auth_key'),$user);
//dump(session::get('authid')); 
echo "<script>alert('数据库添加成功');location.href='http://127.0.0.1/zhuce/index.php/index';</script>";
}
else throw_exception("<script>alert('数据库添加失败');history.back();</script>");
}

第三步:在indexaction.class.php文件中用if(!session::is_set(c('user_auth_key')))判断用户登录了没有。
session::get(c('user_auth_key'))是获取登录用户的名。

具体代码如下:

public function index()
{
if(!session::is_set(c('user_auth_key')))
//if(!isset($_session['user_auth_key'])||($_session['user_auth_key']==0))//不能用此句
{
$msg="用户没有登录"; 
}
else
{
$msg=session::get(c('user_auth_key')).'欢迎你回来';
}
$this->assign('msg',$msg);
$this->display(); 
}

第四步:首页显示模板,代码如下:

<body>
{$msg}<br />
这是我的首页
</body>

小结:

登录代码都是围绕写session,判断session,读session展开。
写session用:session::set(c('user_auth_key'),$user);
判断session用:if(!session::is_set(c('user_auth_key')));
读session用:session::get(c('user_auth_key'))

上述就是thinkphp登录功能的实现方法全部内容。

更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《smarty模板入门基础教程》及《php模板技术总结》。

希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。