use*_*736 6 php cookies session curl
我有以下PHP代码登录到受密码保护的页面并抓取受保护的页面.脚本工作正常,但我想只使用一次登录功能,如果我想在同一域内抓取另一个受保护的页面.
我想使用cookie文件打开下一个受保护的页面,而不是再次使用登录功能!换句话说,我只是想绕过登录步骤来抓取其他受保护的页面.
有人能告诉我这是怎么做到的吗?
注意:我的登录功能不会创建任何cookie我不会在脚本的同一文件夹中看到它!任何人都可以告诉我为什么?
<?
$ch=login();
$html=downloadUrl('http://www.example.com/page1.asp', $ch);
////echo $html;
function downloadUrl($Url, $ch){
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com/");
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
return $output;
}
function login()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.asp'); //login URL
curl_setopt ($ch, CURLOPT_POST, 1);
$post_array = array(
'txtUserName'=>'brad',
'txtPassword'=>'bradpassword',
);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_array);
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$store = curl_exec ($ch);
return $ch;
}
?>
<html>
<br>
<textarea rows="30" cols="150"><?PHP print_r($html); ?></textarea>
</html>
Run Code Online (Sandbox Code Playgroud)
使用
curl_setopt($ch,CURLOPT_COOKIEJAR, $cookieFileLocation);
curl_setopt($ch,CURLOPT_COOKIEFILE, $cookieFileLocation);
Run Code Online (Sandbox Code Playgroud)
在第二个请求中,$cookieFileLocation 是 cookie 文件的位置。
您必须有 2 个请求。首先是填充 cookie 文件的登录请求。
您必须检查您的 cookie 文件是否存在is_file($cookieFileLocation),如果存在,您可以绕过登录过程执行第二个下载受保护内容的请求。
需要注意的是,大多数系统都有会话过期时间,因此您必须在一段时间后重新登录。我会检查返回页面的 html 是否有登录错误,作为我必须再次登录的标记。