sin*_*spi 10 php authentication session curl file-get-contents
我想制作一个可以从网站捕获页面的PHP脚本.想想file_get_contents($ url).
但是,本网站要求您在访问任何页面之前填写用户名/密码登录表单.我想,一旦登录,网站会向您的浏览器发送一个身份验证cookie,并且随后的每个浏览器请求都会将会话信息传递回网站以验证访问权限.
我想知道我如何使用PHP脚本模拟浏览器的这种行为,以获得访问权限并从该网站捕获页面.
更具体地说,我的问题是:
谢谢.
cOl*_*le2 16
Curl非常适合这样做.除了设置CURLOPT_COOKIEJAR和CURLOPT_COOKIEFILE选项之外,您不需要做任何特殊操作.一旦您通过从站点传递表单字段登录,cookie将被保存,Curl将自动使用相同的cookie用于后续请求,如下例所示.
请注意,下面的函数会保存cookie,cookies/cookie.txt以确保目录/文件存在并可以写入.
$loginUrl = 'http://example.com/login'; //action from the login form
$loginFields = array('username'=>'user', 'password'=>'pass'); //login form field names and values
$remotePageUrl = 'http://example.com/remotepage.html'; //url of the page you want to save
$login = getUrl($loginUrl, 'post', $loginFields); //login to the site
$remotePage = getUrl($remotePageUrl); //get the remote page
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies/cookies.txt');
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16833 次 |
| 最近记录: |