Ad

How To Retain Session When Sending Second Request In Curl Php?

My problem is that when I synchronize data from PHP to node js 1st time I logged in to the node.js application. But after logging in when I sending data on second request the session is not sending with curl request hence it is showing that 'not logged in'.

Its my loggin curl code:

$data_string = json_encode(['userid' => $user_name, 'password' => $password]);
$URL = $url;     

$ch = curl_init('http://192.168.1.16:8000/auth/login');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                 
);

$result = curl_exec($ch);

And it is sending data Curl code:

$data_string = json_encode(['import_export' =>$json]);                                                                                   

https://stackoverflow.com/users
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => 'http://192.168.1.16:8000/api/all',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => array(                                                                          
            'Content-Type: application/json',                                                                                
            'Content-Length: ' . strlen($data_string)
        )
    ));

    $result = curl_exec($ch);
Ad

Answer

Tell cURL to use cookies:

curl_setopt(CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt(CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

This way the default Node/Express session cookie based authentication should work since session cookie will be saved upon login and sent with subsequent requests.

http://php.net/manual/en/function.curl-setopt.php

Ad
source: stackoverflow.com
Ad