<?php namespace appapicontroller; use thinkController; use thinkRequest; use thinkValidate; class Common extends Controller { protected $params; //每个控制器的方法对应的请求参数验证规则 protected $rules = [ "User" => [ "login" => [ "username" => "require|max:6", "password" => "require|length:32" ] ] ]; public function initialize() { $params = input(); $time = isset($params['time'])?$params['time']:""; $token = isset($params['token'])?$params['token']:""; $this->check_time($time); $this->check_token($token, $time); $this->check_params($params); } /*验证请求接口时间*/ public function check_time($time) { if($time == "" || time()-$time>60) { $this->return_msg(400, "请求时间超时"); } } /*验证令牌*/ public function check_token($token, $time) { if($token == "" || $token != md5("cain_$time")) { $this->return_msg(400, "token令牌验证失败"); } } /*验证并过滤参数*/ public function check_params($params) { unset($params['time']); unset($params['token']); $validate = Validate::make($this->rules[request()->controller()][request()->action()]); if(!$validate->check($params)) { $this->return_msg(400, $validate->getError()); } else $this->params = $params; } /*返回信息*/ public function return_msg($code, $msg="", $data=[]) { echo json_encode(['code'=>$code, 'msg'=>$msg, "data"=>$data]);die; } }