一、前臺登陸用的form
<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>
二、後臺驗證用戶名密碼,若是登陸成功則寫入session和cookie,若是cookie不設置失效時間,默認是關閉所有瀏覽器時失效
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,'用戶名或密碼錯誤,正在跳轉回登錄頁...');
}
}
三、首頁控制器判斷session或者cookie是否存在
<?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();
}
}
四、首頁頁面模板中,使用標籤判斷用戶信息,顯示不一樣的內容
<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>
五、註銷登陸
public function logout(){
session('uid',null);
session('uname',null);
cookie('uid',null);
cookie('uname',null);
redirect(__APP__);
}