我有一个 php 脚本,正在使用它登录远程站点,并且运行良好。然而,它似乎仅在指定的 cookie 文件名为 cookie.txt
我想要的是每个使用这个脚本的人都有一个单独的cookie文件。因此,如果 machineA 上的某个人在 19 日使用它,他们的 cookie 将位于 /tmp/19/someNameCookie.txt
之类的位置,machineB 将具有 /tmp/19/someOtherNamedCookie。 txt
,如果 machineC 在 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);
?>
关于PHP CURL 创建和使用唯一命名的 cookie 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014666/