基于ThinkPHP的开发笔记3-登录功能(转)
1、前台登录用的form
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
< form id = 'form_login' action = "{:U('runLogin')}" method = "post" > < div class = "row" > < label class = "field" >登陆名 </ label > < div class = "item" > < input id = "address" class = "basic-input" name = "uname" maxlength = "70" size = "46" /> </ div > </ div > < div class = "row" > < label class = "field" >密码 </ label > < div class = "item" > < input id = "pwd" class = "basic-input" type = "password" name = "pwd" maxlength = "70" size = "46" /> </ div > </ div > < div class = "row" > < div class = "item" > < input type = "checkbox" name = 'auto' class = 'auto' id = 'auto' checked = '1' /> < label for = "auto" >记住我,下次自动登录</ label > </ div > </ div > < hr class = "hrline" /> < div class = "row footer" > < div class = "item" > < input class = "loc-btn" type = "button" id = "submit_form" value = "提交" /> < input class = "lnk-flat" type = "button" id = "cancel_form" value = "取消" /> </ div > </ div > </ form > |
2、后台验证用户名密码,如果登录成功则写入session和cookie,如果cookie不设置失效时间,默认是关闭全部浏览器时失效
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public function runLogin(){ if (! $this ->isPost()){ halt( '页面不存在' ); } $uname =I( 'post.uname' ); $pwd =I( 'post.pwd' , '' , 'md5' ); $auto =I( 'post.auto' ); $condition = array ( 'uname' => $uname , 'pwd' => $pwd ); $user =M( 'User' )->where( $condition )->find(); if ( $user ){ $uid = $user [id]; if ( $user [nickname]){ $uname = $user [nickname]; } session( 'uid' , $user [id]); session( 'uname' , $uname ); if ( $auto == 'on' ){ cookie( 'uid' , $uid ,30*24*3600); cookie( 'uname' , $uname ,30*24*3600); } header( 'Content-type:text/html;Charset=UTF-8' ); redirect(__APP__); } else { header( 'Content-type:text/html;Charset=UTF-8' ); redirect(U( 'login' ),2, '用户名或密码错误,正在跳转回登陆页...' ); } } |
3、首页控制器判断session或者cookie是否存在
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php // 首页控制器 class IndexAction extends Action { public function index(){ $data =session( 'uname' ); if ( $data ){ $this ->data = $data ; } else if (cookie( 'uname' )){ $this ->data = cookie( 'uname' ); } $this ->display(); } } |
4、首页页面模板中,使用标签判断用户信息,显示不同的内容
1
2
3
4
5
6
7
8
9
|
< div id = 'login' class = 'right' > < empty name = "data" > < a href = '{:U(' Login/login')}'>登录</ a > < a href = '{:U(' Login/register')}'>注册</ a > < else /> < a href = '#' >欢迎 {$data}</ a > < a href = '{:U(' Login/logout')}'>注销</ a > </ empty > </ div > |
5、注销登录
1
2
3
4
5
6
7
|
public function logout(){ session( 'uid' ,null); session( 'uname' ,null); cookie( 'uid' ,null); cookie( 'uname' ,null); redirect(__APP__); } |