php用户操作记录,及防止url跳过登录

php如何防止别人跳过登录直接访问你的控制器,方法有很多,其中一种就是token

思路,创建用户表时,就直接加一个token字段,用来存储token,前端会在JS公共的加一个token,加了之后,每个页面都会多一个token,此时便可以通过token判断是哪个用户做了什么。以便记录。

实战: 

  1. 数据库设计

 

  1. 登录接口
 public function Login(){
        try{
            $username = $_REQUEST['username'];
            $password = $_REQUEST['password'];
            $password = trim($password);
            $password = md5(md5($password) . sha1($password));

            if(empty($username))
            {
                throw new Exception("请输入用户名");
            }

            if(empty($password))
            {
                throw new Exception("请输入密码");
            }

            $tableName = 'user';
            $sql = "select * from " . $tableName . " where username='" . $username . "' and password='" .$password. "'";
            $res = Db::query($sql);
            if(!(is_array($res) && !empty($res)))
            {
                throw new Exception("用户名或密码错误");
            }
            $userInfo = $res[0];

            $token = $this->getUserToken(32);

            $table = 'user';
            $data = array(
                'token' => $token,
                'token_create' => time(),
                'expire' => '3600'
            );
            $where = array(
                'id' => $userInfo['id']
            );
            $code = Db::table($table)->where($where)->update($data);

            $result = array(
                'id' => $userInfo['id'],
                'token' => $token,
                'username' => $userInfo['username'],
                'user_type' => $userInfo['type'],
            );

            $this->ajaxReturn(array(
                'code' => 1,
                'msg' => '登录成功',
                'data' => $result,
            ));
        }catch(Exception $e){
            $this->ajaxReturn(array(
                'code' => -1,
                'msg' => $e->getMessage()
            ));
        }
    }

    function getUserToken($length)
    {
        $length = abs($length);
        $n = max(1, 32 - $length);
        $n = mt_rand(0, $n);
        return substr(md5(uniqid()), $n, $length);
    }

    private function ajaxReturn($data)
    {
        header('Content-Type:application/json; charset=UTF-8');
        echo json_encode($data);
        exit;
    }


      3.基础控制器 $username = $_REQUEST['username'];
            $pas

class BaseController extends Controller{

    /**
     * 控制器名
     */
    protected $controller;

    /**
     * 动作方法名,字符串中不包括on
     */
    protected $action;

    /**
     * 当前登录用户信息
     */
    protected $user;

    public function __construct () {
        $headers = getallheaders();
//        if ($headers['X-Requested-With'] != 'XMLHttpRequest') {
//            exit;
//        }

//        print_r($_SERVER);

        if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') {
            exit;
        }

//        $token = isset($headers['Authorization']) ? $headers['Authorization'] : '';
        $token = isset($headers['Authorization']) ? $headers['Authorization'] : (isset($headers['authorization']) ? $headers['authorization'] : '');
        $flag = false;
        if($token)
        {
            $tableName = 'user';
            $sql = "select * from " . $tableName . " where token='" . $token . "' ";
            $model = Model::Agg();
            $res = $model->getLocalData($sql);
            if(isset($res[0]) && !empty($res[0]))
            {
                $expireTime = intval($res[0]['token_create']) + intval($res[0]['expire']);
                if($expireTime > time())
                {
                    $this->user = $res[0];
                    $flag = true;
                }
            }
        }

        if(!$flag)
        {
            //未登录,跳转到登录页
            $this->ajaxReturn(array(
                'code' => 401,
                'msg' => 'Unauthorized'
            ));
        }
    }

    /**
     * 当前登录用户信息
     */
    public function getUserInfo()
    {
        return $this->user;
    }

    /**
     * 当前登录用户id
     */
    public function getUserId()
    {
        $userInfo = $this->user;
        $id = isset($userInfo['id']) ? $userInfo['id'] : '';
        return $id;
    }

    /**
     * 当前登录用户名
     */
    public function getUserName()
    {
        $userInfo = $this->user;
        $username = isset($userInfo['username']) ? $userInfo['username'] : '';
        return $username;
    }

    /**
     * 当前登录用户类型
     */
    public function getUserType()
    {
        $userInfo = $this->user;
        $type = isset($userInfo['type']) ? $userInfo['type'] : '';
        return $type;
    }

    /**
     * 当前登录用户id
     */
    public function isLogin()
    {
        return $this->user ? true : false;
    }

    /**
     * 验证token
     */
//    public function checkToken()
//    {
//        $headers = getallheaders();
//        $token = isset($headers['Authorization']) ? $headers['Authorization'] : '';
//       $flag = false;
//        if(empty($this->user))
//        {
//            header('HTTP/1.1 401 Unauthorized');
//            header('status: 401 Unauthorized');
//
//           header('HTTP/1.1 200 ok');
//           header('status: 200 ok');
//            exit;
//        }
//
//    }

    /**
     * 封装跳转
     */
   #  public function redirect($url){
   #     header('location:' . $url);
   #     exit;
   # }

    public function ajaxReturn($data)
    {
        header('Content-Type:application/json; charset=UTF-8');
        echo json_encode($data);
        exit;
    }

sword = $_REQUEST['password'];
            $password = trim($passworassword = md5(md5($password) . sha1($pas
            if(empty($username))
      
                throw new Exception("请输入用户名");
            }

            if(empty($password))
            {
                throw new Exception("请输入密码");
            }

            $tableName = 'user';
            $sql = "select * from " . $tableName . " where username='" . $username . "' and password='" .$password. "'";
            $res = Db::query($sql);
            if(!(is_array($res) && !empty($res)))
            {
                throw new Exception("用户名或密码错误");
            }
            $userInfo = $res[0];

            $token = $this->getUserToken(32);

            $table = 'user';
            $data = array(
                'token' => $token,
                'token_create' => time(),
                'expire' => '3600'
            );
            $where = array(
                'id' => $userInfo['id']
            );
            $code = Db::table($table)->where($where)->update($data);

            $result = array(
                'id' => $userInfo['id'],
                'token' => $token,
                'username' => $userInfo['username'],
                'user_type' => $userInfo['type'],
            );

            $this->ajaxReturn(array(
                'code' => 1,
                'msg' => '登录成功',
                'data' => $result,
            ));
        }catch(Exception $e){
            $this->ajaxReturn(array(
                'code' => -1,
                'msg' => $e->getMessage()
            ));
        }
    }

    function getUserToken($length)
    {
        $length = abs($length);
        $n = max(1, 32 - $length);
        $n = mt_rand(0, $n);
        return substr(md5(uniqid()), $n, $length);
    }

    private function ajaxReturn($data)
    {
        heade

class BaseController extends Controller{

    /**
     * 控制器名
     */
    protected $controller;

    /**
     * 动作方法名,字符串中不包括on
     */
    protected $action;

    /**
     * 当前登录用户信息
     */
    protected $user;

    public function __construct () {
        $headers = getallheaders();
//        if ($headers['X-Requested-With'] != 'XMLHttpRequest') {
//            exit;
//        }

//        print_r($_SERVER);

        if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') {
            exit;
        }

//        $token = isset($headers['Authorization']) ? $headers['Authorization'] : '';
        $token = isset($headers['Authorization']) ? $headers['Authorization'] : (isset($headers['authorization']) ? $headers['authorization'] : '');
        $flag = false;
        if($token)
        {
            $tableName = 'user';
            $sql = "select * from " . $tableName . " where token='" . $token . "' ";
            $model = Model::Agg();
            $res = $model->getLocalData($sql);
            if(isset($res[0]) && !empty($res[0]))
            {
                $expireTime = intval($res[0]['token_create']) + intval($res[0]['expire']);
                if($expireTime > time())
                {
                    $this->user = $res[0];
                    $flag = true;
                }
            }
        }

        if(!$flag)
        {
            //未登录,跳转到登录页
            $this->ajaxReturn(array(
                'code' => 401,
                'msg' => 'Unauthorized'
            ));
        }
    }

    /**
     * 当前登录用户信息
     */
    public function getUserInfo()
    {
        return $this->user;
    }

    /**
     * 当前登录用户id
     */
    public function getUserId()
    {
        $userInfo = $this->user;
        $id = isset($userInfo['id']) ? $userInfo['id'] : '';
        return $id;
    }

    /**
     * 当前登录用户名
     */
    public function getUserName()
    {
        $userInfo = $this->user;
        $username = isset($userInfo['username']) ? $userInfo['username'] : '';
        return $username;
    }

    /**
     * 当前登录用户类型
     */
    public function getUserType()
    {
        $userInfo = $this->user;
        $type = isset($userInfo['type']) ? $userInfo['type'] : '';
        return $type;
    }

    /**
     * 当前登录用户id
     */
    public function isLogin()
    {
        return $this->user ? true : false;
    }

    /**
     * 验证token
     */
//    public function checkToken()
//    {
//        $headers = getallheaders();
//        $token = isset($headers['Authorization']) ? $headers['Authorization'] : '';
//       $flag = false;
//        if(empty($this->user))
//        {
//            header('HTTP/1.1 401 Unauthorized');
//    header('Content-Type:application/json; charset=UTF-8');
        echo json_encode($data);
 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值