PHP模拟post登陆并获取数据

<?php
$cookie_file    =    tempnam('./temp','cookie'); //设置cookie目录
$url        =    'post提交地址';
$fields    =    '提交post的内容';

//以下是用CURL来模拟登入并获取并保存Cookie
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_HEADER, 0);//获取文件头
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//是否回显
curl_setopt($ch, CURLOPT_POST, 1); //使用post方式提交
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //提交post内容
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); //保存cookie
curl_exec($ch); //执行
curl_close($ch); //关闭

//CURL用保存的cookie去访问需要登入的页面并获取内容
$url='需要登入后查看的页面';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);  //获取文件头
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //是否回显
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); //附带已保存的cookie
$contents = curl_exec($ch); //获取内容
curl_close($ch);  //关闭curl
?>
赞 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址