PHP curl模拟用户登陆获取数据

在一些场景下,一些数据需要用户登陆才能获取。因为我们可以做模拟登陆。

//模拟登陆
function loginPost($url, $cookie, $post){
    $ch = curl_init(); //初始化curl模块
    curl_setopt($ch, CURLOPT_URL, $url); //登录提交的地址
    curl_setopt($ch, CURLOPT_HEADER, 0); //是否显示头信息
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); //是否自动显示返回的信息
    //模拟浏览器
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36');
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); //本地中保存的cookie
    curl_setopt($ch, CURLOPT_POST, 1); //以POST方式提交
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));//传递参数
    curl_exec($ch); //执行CURL
    curl_close($ch);
}

//获取数据
function getContent($url, $cookie,$param){
    $ch = curl_init(); //初始化curl模块
    curl_setopt($ch, CURLOPT_URL, $url); //登录提交的地址
    curl_setopt($ch, CURLOPT_HEADER, 0); //是否显示头信息
    //模拟浏览器
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //是否自动显示返回的信息
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);//传cookie值
    curl_setopt($ch, CURLOPT_POST, 1); //以POST方式提交
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));//传递参数
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
    ));
    //var_dump($param);exit;
    $rs = curl_exec($ch); //执行curl转去页面内容
    curl_close($ch);
    return $rs; //返回字符串
}

// 模拟登陆账号密码
$post = array(
    'username' => '123',
    'password' => '123',
    'remember-me' => 'on'
);
$param=array(
'type'=>1,
'status'=>2
); $urlLogin
= "http://test.jackzhuo.com/login"; //登录地址 $cookie = dirname(__FILE__).'/data/cookieLogin.txt'; //设置cookie保存的路径 $url="http://test.jackzhuo.com/billing/customer/customerDetailList";//获取数据地址 loginPost($urlLogin, $cookie, $post); //调用模拟登录 $content = getContent($url,$cookie,$param); //登录后,获取登录后指定的页面信息 $customer=dirname(__FILE__)."/data/data".date('YmdHis').".json"; $res=file_put_contents($customer,$content);

 

posted @ 2021-02-06 09:27  离岸少年  阅读(216)  评论(0编辑  收藏  举报