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;
}
此工作的請客我想要的東西 - 感謝 – Chris 2011-04-10 11:07:29