PHP CURL创建和使用唯一命名的cookie文件

时间:2012-08-18 00:11:33

标签: php curl

我有一个用于登录远程站点的PHP脚本,它运行良好。但是,它似乎仅在指定的cookie文件名为cookie.txt

时才有效

我想要的是每个使用此脚本的人都有一个单独的cookie文件。因此,如果机器A上的某个人在19日使用它,那么cookie将位于类似/tmp/19/someNameCookie.txt的内容中,machineB将具有/tmp/19/someOtherNamedCookie.txt,如果machineC在20日使用它,则它们将具有{{1} }}

有很多方法可以生成唯一命名的文件,但这里的关键是让它们工作。我非常年轻的PHP知识和全新的卷曲。

另一方面,我也没有成功使用/tmp/20/someNamedCookie.txt来获取登录产生的新页面。

感谢。


这是一段代码。从另一个来源得到了这个。

CURLOPT_FOLLOWLOCATION

这是我之后调用的代码,用于检查登录是否成功

$username=urlencode($usr); 
$password=urlencode($pass); 
$url="http://domain.com/"; 
$cookie="cookie.txt"; 

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
curl_setopt ($ch, CURLOPT_TIMEOUT, 60); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie); // have tried with just the jar, and just the file and both 
curl_setopt ($ch, CURLOPT_REFERER, $url); 

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); 
curl_setopt ($ch, CURLOPT_POST, 1); 
$result = curl_exec ($ch);

echo $result;  
curl_close($ch);

根据我的理解,curl应该创建cookie文件(如果它不存在)。我也尝试使用fopen手动创建其他文件,但是只有在我使用cookie.txt时才能正常工作,现在它只是为了测试而被保存到public_html。

2 个答案:

答案 0 :(得分:5)

设置Cookie Jar

<?php
    $machine = 'PC_A'; // here it's your problem how you define each machine
    $cookie_file = "/tmp/".date('d')."/".$machine."_cookie.txt";
    // and set the cURL cookie jar and file

    if (!file_exists($cookie_file) || !is_writable($cookie_file)){
            echo 'Cookie file missing or not writable.';
            die;
    }

    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
?>

答案 1 :(得分:0)

对于cookie文件名使用例如session_id(),它对于连接到您的应用程序的每台机器都是唯一的,并且在它到期之前它仍然是相同的