php curl cookie 存取示例

好多人发来消息询问curl存取cookie文件的问题,不觉得这是个难点,因为只看手册就可以很容易把握。下面给个例子,看完后就全都明了了:

<?php
$cookie_jar_index = 'cookie.txt';

$url = "http://www.71j.cn/perl/login.pl";
$params = "username=dudu&password=****";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar_index);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
//curl_setopt($ch, CURLOPT_NOBODY, 1);//这个不能打开,否则无法生成cookie文件
ob_start();
curl_exec($ch);
curl_close($ch);
ob_clean();

$url = "http://www.71j.cn/perl/myfavorites.pl";
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_COOKIEFILE, $cookie_jar_index);
ob_start();
curl_exec($ch2);
curl_close($ch2);
$rs = ob_get_contents(); //$rs就是返回的内容
ob_clean();

print_r($rs);

?>

Leave a Reply

Your email address will not be published. Required fields are marked *