卷曲饼干不是在成功创造

时间:2010-03-29 12:13:23

标签: php cookies curl

我正在使用cUrl(PHP)在cookie文件中发布登录请求和存储响应。 在我的第二个请求中,我在标题中传递cookie并发布数据以验证它。

问题是第一次成功请求中没有创建cookie文件导致第二次请求失败。请建议我在哪里做错了。

$cookiefile="/var/www/html/dimdim/cook.txt";
$url_log="http://my.dimdim.com/api/auth/login";
$p_log='request={"account":"bin6k","password":"password","group":"all"}';
$url_ver="http://my.dimdim.com/api/auth/verify";
$p_ver='request={"account":"bin6k","password":"password","group":"all"}';

$ch = curl_init();
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);

curl_setopt($ch, CURLOPT_URL,$url_log);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $p_log);

ob_start();      // prevent any output
$retval=curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output
curl_close ($ch);
//print_r($retval);
unset($ch);


$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($ch, CURLOPT_URL,$url_ver);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $p_log);

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);

3 个答案:

答案 0 :(得分:3)

我有同样的问题用于在windows localhost服务器上运行

curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/cookies.txt");

答案 1 :(得分:0)

尝试在其中添加curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

此外,无需为每个请求启动新的curl实例。您可以为多个请求重用相同的实例。只需在每次设置适当的CURLOPT(url,postfields,get等等),curl将在内部对事物进行排序。

答案 2 :(得分:0)

尝试此功能添加cookijar选项:

function execute($toLoad) {

    if ( !preg_match( '/^http/', $toLoad ) ) {
        $toLoad = 'http://'.$toLoad;
    }
    $cookiefile = APP_PATH.'tmp/cookie.txt';
    $data = array();    
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);
    curl_setopt($ch, CURLOPT_TIMEOUT,10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.6) Gecko/20091216 Fedora/3.5.6-1.fc11 Firefox/3.5.6 GTB6");
    curl_setopt($ch, CURLOPT_URL, $toLoad); // The page to download
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, 'http://somesite.com/' ); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);    

    $data['data'] = curl_exec($ch);
    $data['status'] = curl_getinfo($ch);

    //$this->out(curl_error($ch));   
    //$this->out(curl_getinfo($ch));     
    //$this->out('');
    //$this->out($data);
    //$this->out('');

    curl_close($ch);

    return $data;
}

你也可以尝试读取Set-Cookie的返回数据的标题:SOMEKEY

然后在curlopt中使用

if ($header) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cookie:'.$header)); 
} 

由于