gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:33:37 24 4
gpt4 key购买 nike

我有一个用于登录远程站点的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com