Search code examples
phpcurljsessionid

How to set JSESSIONID in cookie on php curl?


Im trying to integrate 3rd part API in PHP curl.

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.

Anyone know about this?

PHP code

$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);

Solution

  • The URL you're accessing is trying to set cookies.

    To accept cookies with cURL, you'll need to specify a "cookie jar", a file where cURL can store the cookies it receives:

    // 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.