这通常对我有用
$timeout=5;
$file='cookies.jar';
$this->handle=curl_init('');
curl_setopt($this->handle, CURLOPT_COOKIEFILE, $file);
curl_setopt($this->handle, CURLOPT_COOKIEJAR, $file);
curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)");
curl_setopt($this->handle, CURLOPT_TIMEOUT, round($timeout,0));
curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, round($timeout,0));
我一般都是这样用的
$now=grab_first_page();
if(not_logged_in($now)) {
send_login_info();
}
if(not_logged_in()) { end_of_script_with_error(); }
// rest of script
这样 cookie 会跨会话保存,并且脚本不必在每次执行某些操作时都登录。
---解释如下----
我正在使用一个对象,但您可以将 $this->handle 替换为一个名为 $mycurl 的简单变量,这些行将类似于
$mycurl=curl_init(''
curl_setopt($mycurl, CURLOPT_COOKIEFILE, $file)
以下代码的作用是:
- 初始化“一个 curl 实例”(为了简单起见)(第 3 行)
- 第 4 和第 5 行:将 cookie 保存到文件中。 curl 就像浏览器一样工作,因此当您使用 curl 登录页面时,它会将带有身份验证数据的 cookie 保存在内存中。我告诉它把它保存到一个文件中,这样我第二次运行脚本时它就会有相同的 cookie,并且不需要再次进行身份验证。或者,您可以使用同一个 cookie 文件拥有多个脚本,并且每 24 小时运行一次或在您注销时运行一个用于登录的脚本......
- 其他设置:
* followlocation - 当 curl 接收到一个 http 重定向它应该返回它被重定向到的页面,而不是重定向代码
* useragent - curl 将自己呈现为 firefox
* timeout - 等待建立连接的时间,通常 5 或 10 就足够了
我在这里放了一个简单的类http://pastebin.com/Rfpc103X
你可以这样使用它
// -- initialize curl
$ec=new easyCurl;
// -- set some options
//if the file you are in right now is named file_a.php it will create a file_a.jar cookie file
$ec->start(str_replace('.php','.jar',__FILE__));
$ec->headersPrepare(false);
$ec->prepareTimeOut(20);
$url='http://www.google.com/';
// --- set url
$ec->curlPrepare($url);
// --- get the actual data
$page=$ec->grab();
echo $page;
// to send GET data
$get_data=array('id'=>10);
$ec->curlPrepare($url,$get_data);
// and to post data
$post_data=array('user'=>'blue','password'=>'black');
$ec->curlPrepare($url,array(),$post_data);
它会自动处理我经常遇到的 POST/GET 和其他选项的设置。我希望上面的例子对你有用。祝你好运。