卷曲非常适合这样做。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;
}