php 判断是否登录

<?php
// 本类由系统自动生成,仅供测试用途
class IndexAction extends Action {
	public function _before_index(){
		//做判断,如果没有登录,跳转到登录页面
		if(!isset($_SESSION['username']) || $_SESSION['username']=='')
		{
			$this->redirect('Login/index');
		}
		
		
		
	}
    public function index(){
	$city=M('city'); //返回Model实例
	//返回数组
	$arr=$city->select();
	//dump($arr);
	$this->assign('list',$arr);
	$this->display();
    }
	
	public function next(){
		$this->display();
	}
}

//如果没有登录打开index/index.html 会跳转到Login/index 页面

//登录接口:

<?php
   class LoginAction extends Action{
	   function index(){
		   $this->display();
	   
   }
  public function do_login() {
	  $username=$_POST['username'];
	  $password=$_POST['password'];
	  $user=M('user');
	  $where['username']=$username;
	  $where['passord']=$password;
	  $c=$user->where($where)->count();
	  
	  if ($c>0){
		  //必须向SESSION里写数据,不然跳转到Index/index 
		  $_SESSION['username']=$username;
		  $this->redirect('Index/index');
	  }else{
       $this->error('用户不能登录');
	  }
	  
  }
   }
?>


 //必须向SESSION里写数据,不然跳转到Index/index 
 会检测if(!isset($_SESSION['username']) || $_SESSION['username']=='') 如果没有$_SESSION['username']值 又会跳转到登录页面,造成死循环

 
 
 //登录页面:
 
 <!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
   <!-- __URL__: 会替换成当前模块的URL地址(不含域名) -->
   <!-- Login模块下的do_login处理 -->
    <form action="__URL__/do_login"  method='post'>
	  用户名:<input type='text' name='username'/><br/>

	  密码:<input type='password' name='password'/><br/>

	  <input type='submit' value='登录'/>
      </form>
 </body>
</html>

原文地址:https://www.cnblogs.com/zhaoyangjian724/p/6200123.html