tp5登陆接口

use think\Controller;
use think\Db;
use think\Request;

class User extends Controller
{
	public function login(Request $request)//登陆接口
	{
		header('Access-Control-Allow-Origin:*');
		if($request->isPost()){
			$data=input('post.');
			$result = $this->validate($data,'User');
			if(true !== $result){
				return json(['status' => 'error','msg' => '用户名或者密码格式不正确!']);
			}
			$password=substr(md5($data['apassword']),8,16);
			$result=Db::name('user')->where('username',$data['ausername'])->where('password',$password)->find();
			if($result){
				switch ($result['status']) {
					case '0':
					case '1':
					session('userid', $result['id']);
					return json(['status' => 'success','msg' => '登陆成功!']);
					break;
					case '2':
					return json(['status' => 'error','msg' => '用户已被禁用,请联系管理员!']);
					break;
				}
			}else{
				return json(['status' => 'error','msg' => '用户名或者密码错误!']);
			}
		}
	}
}
check_login();
    }
	protected function check_login(){
		$userid=session('userid');
		if(empty($userid)){
			$this->redirect('api/user/login');
		}
	}
}
  'require|max:20',
        'apassword' =>  'require|max:20',
    ];
    
    protected $message = [
        'ausername.require'  =>  '请输入用户名',
        'ausername.max'  =>  '用户名不能超过20个字符',
        'apassword.require' =>  '请输入密码',
        'ausername.require'  =>  '密码不能超过20个字符',
    ];
}
$("#login").click(function (){
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "http://localhost/tp5/public/index.php/api/user/login" ,//登陆接口路径
        data: $('#form1').serialize(),
        success: function (result) {
            if(result.status=='success'){
                window.location.href="index.html";
            }else if(result.status=='error'){
                alert(result.msg);
                return false;
            }
        },
        error : function() {
            alert("登陆失败!");
        }
    });
});




	
	
	
	首页


Hello World!




你可能感兴趣的:(php,thinkphp5)