简体   繁体   中英

How to send cookie in request to API In php via Curl

I am having HTTP cookie based Authentication,After Authentication i get cookie in response,

Another step is to send cookie in request to API. along with post/get request

Below Example is of my Curl

$cookie_jar= $_COOKIE['DesigntoolAuth'];
//$ch = curl_init($url);                                                                      
// The data to send to the API
$postData = array(
    'ProjectId' => $projectId,
    'ProjectName' => $proname,
    'ProjectDetails' => $details, 
    'UserId' => $userId
);

$data_string = json_encode($postData);  
// Setup cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   
curl_setopt($ch, CURLOPT_VERBOSE, true);  
curl_setopt($c, CURLOPT_COOKIEFILE, $cookie_jar);                                                                 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json'                                                                             
    //'Content-Length: ' . strlen($data_string)
    ));                                                                   

    $api_result =  curl_exec($ch);
    echo $api_result;

Can Anybody tell how ti send the cookie ?

From the cURL PHP reference :

CURLOPT_COOKIEFILE

The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

This means that the CURLOPT_COOKIEFILE needs to refer to a file which contains the cookies you need to send. The file is a file which exists on the server running cURL, which, in turn, will transmit the cookie data to the remote host. I'd expect read access to be required on the file.

A good answer describing how the Netscape format looks like can be found here

In addition, if you want to keep the cookies that are generated during the request, you also need to set a CURLOPT_COOKIEJAR .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM