【问题标题】:How to set JSESSIONID in cookie on php curl?如何在 php curl 的 cookie 中设置 JSESSIONID?
【发布时间】:2020-05-11 17:54:11
【问题描述】:

我正在尝试将第 3 部分 API 集成到 PHP curl 中。

当我在postman 中尝试时,它工作正常并得到了响应。但它不适用于我的 PHP CURL 代码。

我发现在邮递员的标题中设置了 JSESSIONID。我不知道如何在 php curl 中创建该 JSESSIONID 并在 cookie 中设置。

有人知道吗?

PHP 代码

$url = "http://website.com/Public/login/";
$dataa["userNo"] = "username";
$dataa["userPassword"] = "password";

$data = json_encode($dataa);

$ch = curl_init($url);

$headers = array(
        'Content-type: application/json',
        "Cookie: JSESSIONID=2cba2d9d7dc5455b76t90f4ccac3; httpOnly"
    );


curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Instruct cURL to store cookies in this file.
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');

// Instruct cURL to read this file when asked about cookies.
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');

$response1 = curl_exec($ch);

curl_close($ch);
$res = json_decode($response1,true);

【问题讨论】:

  • 给定的代码有什么不工作的地方吗?
  • @NicoHaase,感谢您的回答。但它不起作用。我已在问题部分更新了我的代码
  • “不工作”是对您的问题的相当广泛的描述。你能解释一下这是什么意思吗?
  • cookie 文件中没有值。

标签: php curl jsessionid


【解决方案1】:

您正在访问的 URL 正在尝试设置 cookie。

要接受带有 cURL 的 cookie,您需要指定一个“cookie jar”,这是一个 cURL 可以存储它接收到的 cookie 的文件:

// Instruct cURL to store cookies it receives in this file.
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');

// Instruct cURL to read this file when asked about cookies.
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

JSESSIONID 听起来像一个“会话 ID”cookie,用于跟踪会话或一系列请求。会话 ID 2cba2d9d7dc5455b76t90f4ccac3 与您使用 Postman 启动的会话相关联,您需要将其从 PHP 请求中删除。

【讨论】:

  • 更具体地说,发明自己的JSESSIONID 值是没有意义的。它不会起作用。
  • 刚刚更改了cookie文件路径,如./cookies.txt
  • @Vel 您可能需要一个专用目录来存放 cookie 数据和类似内容(如答案所示),而不是使用当前工作目录并存储分散在源代码中的临时文件。
猜你喜欢
  • 2015-03-13
  • 2021-07-22
  • 2012-06-22
  • 2014-10-27
  • 1970-01-01
  • 2016-12-10
  • 2017-02-04
  • 2012-09-26
  • 2017-11-24
相关资源
最近更新 更多