カールはそれを行うのに非常に適しています。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;
}