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


PHP CURL creating and using uniquely named cookie files

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

我想要的是让每个使用此脚本的人都有一个单独的 cookie 文件。因此,如果机器A上的人在19日使用它,他们的cookie将位于类似/tmp/19/someNameCookie.txt,机器B将具有/tmp/19/someOtherNamedCookie.txt,如果机器C在20日使用它,他们将拥有/tmp/20/someNamedCookie.txt

有许多方法可以生成唯一命名的文件,但这里的关键是让它们工作。我对 php 知识非常年轻,对 curl 完全陌生。

附带说明一下,我也没有成功使用 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);

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

$ch2 = curl_init();
//curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch2, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch2, CURLOPT_URL, "http://domain.com/");
$r = curl_exec($ch2);
echo $r;
curl_close($ch2);

据我了解,如果 cookie 文件不存在,curl 应该创建它。我还尝试使用 fopen 手动和通过脚本创建其他文件,但仍然仅在我使用 cookie.txt 时才有效,现在它全部保存到 public_html 中只是为了测试。

设置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);
?>
例如

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