如何在php中使用curl保持会话信息?

时间:2014-07-24 07:13:44

标签: php curl

只有在我首先登录时才可以访问虚构页面www.randomDomain.com/onlyForRegisteredUsers。所以 我这样做了:

...
curl_setopt($this->curl, CURLOPT_HEADER, false);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->curl, CURLOPT_HTTPPROXYTUNNEL, true);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 10);
curl_setopt($this->curl, CURLOPT_USERAGENT, $this->currentUseragent;
curl_setopt($this->curl, CURLOPT_PROXY, $this->currentIP);
curl_setopt($this->curl, CURLOPT_URL, $this->currentUrl); //www.randomDomain.com/login/
curl_setopt($this->curl, CURLOPT_POST, true);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->currentData);
    //with login RandomUserName and pass *******
$page = curl_exec($this->curl);

并且在$ page中我成功得到了这样的结果:...<p>Welcome back, RandomUserName!</p>

如何保存有关我已登录的会话的信息,然后从www.randomDomain.com/onlyForRegisteredUsers读取内容?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

$cookieFile = 'cookie.txt';
curl_setopt($this->curl, CURLOPT_COOKIESESSION, true);
curl_setopt($this->curl, CURLOPT_COOKIEJAR, realpath($cookieFile));
curl_setopt($this->curl, CURLOPT_COOKIEFILE, realpath($cookieFile));

注意:cookie文件必须存在,如果不存在,则可以创建文件:

if (!file_exists(realpath($cookieFile)))
{
    touch($cookieFile);
}