如何在php curl的cookie中设置JSESSIONID?

我正在尝试在PHP curl中集成第三方API。

It is working fine and got the response when I tried in postman. But it is not working in my PHP CURL code.

enter image description here I find the there is JSESSIONID is set in header in postman. I don't know how to create that JSESSIONID in php curl and set in cookies.

有人知道吗?

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);
评论
  • 别掏心
    别掏心 回复

    您正在访问的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 sounds like a "session ID" cookie, something that keeps track of a session, or a series of requests. The session ID 2cba2d9d7dc5455b76t90f4ccac3 is tied to the session you started with Postman, you'll need to remove that from your PHP request.