<?php
 
namespace app\index\controller;
 
use app\common\controller\Frontend;
use think\Session;
 
class Index extends Frontend
{
 
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
 
    function getToken(){
        return $this->request->token();
    }
 
 
    public function testToken(){
 
       $token = $this->httpRequest('http://faplugin.t.com/index/index/getToken');
     //     $token = $this->request->token();  // 验证失败
        $post_data = array(
            'url' => 'http://fa.withoutfear.cn/index/user/index.html',
            '__token__' => $token,
            'account' => '11111',
            'password' => '901212',
            'keeplogin' => 1
        );
 
        $login_url = 'http://faplugin.t.com/index/index/login'; // 登录表单提交地址
        dump($this->httpRequest($login_url,$post_data));
        die;
 
    }
 
    function login(){
        $data = $this->request->post();
        $validate = new \think\Validate([
            'account'  => 'require|max:25|token'
        ]);
 
        //验证表单令牌方式①
        $result = $validate->check($data);
        if(!$result){
            exit($validate->getError());
        }else{
            exit('登录成功1');
        }
 
        //验证表单令牌方式②
        $token = $this->request->post('__token__');
        if (!$token || !\think\Validate::is($token, "token", ['__token__' => $token])) {
            exit('token验证失败');
        }else{
            exit('登录成功2') ;
        }
    }
 
 
    function httpRequest($url = '',$data = []){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');  // 在访问其他页面时拿着这个cookie文件去访问
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // 将登录后的cookie存储到文件中
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
 
 
}

验证表单令牌

    protected function token($value, $rule, $data)
    {
        $rule = !empty($rule) ? $rule : '__token__';
 
        if (!isset($data[$rule]) || !Session::has($rule)) {
            return false;
        }
 
 
        // 令牌验证
        if (isset($data[$rule]) && Session::get($rule) === $data[$rule]) {
            // 防止重复提交
            Session::delete($rule); // 验证完成销毁session
            return true;
        }
        // 开启TOKEN重置
        Session::delete($rule);
        return false;
    }

发表评论

邮箱地址不会被公开。 必填项已用*标注