Ketan Mujumdar
Ketan Mujumdar

Reputation: 113

Cross domain for maintaining browser session using CURL

I am making a CURL get request via php to another domain to get json value, but as i know curl uses temporary session, but how can i maintain all the browser session in curl request ? here is my code

    // create curl resource 
    $ch = curl_init(); 

    // set url 
    curl_setopt($ch, CURLOPT_URL, "http://api.json");  //api.json is displaying value from session 

    //return the transfer as a string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    curl_setopt($ch, CURLOPT_COOKIESESSION, true);

    // $output contains the output string 
    $output = curl_exec($ch); 

    // close curl resource to free up system resources 
    curl_close($ch);  

how can i maintain the browser session ...

Upvotes: 0

Views: 4071

Answers (2)

Ketan Mujumdar
Ketan Mujumdar

Reputation: 113

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            
        $cookie_value = $cookie_name.'='.$_SESSION[$cookie_name];
        curl_setopt($ch, CURLOPT_COOKIE, $cookie_value);            
        $xml_contents = curl_exec ($ch);
        curl_close ($ch);
        return $xml_contents;   

For this you need to store the cookie and in next request attach into the header that works .

Upvotes: 0

Another Code
Another Code

Reputation: 3151

You can use the CURLOPT_COOKIEJAR option (see documentation) to save all cookies to a file. You can import this file at a later time using the CURLOPT_COOKIEFILE option, this will send all cookies stored in the specified jar.

Example based on your code for keeping a persistent session between script executions:

// create curl resource 
$ch = curl_init(); 

// set url 
curl_setopt($ch, CURLOPT_URL, "http://api.json");  //api.json is displaying value from session 

//return the transfer as a string 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

// Set the cookie jar for both importing and exporting
curl_setopt($ch, CURLOPT_COOKIEFILE, "curl-cookie-session.tmp");
curl_setopt($ch, CURLOPT_COOKIEJAR, "curl-cookie-session.tmp");

// $output contains the output string 
$output = curl_exec($ch); 

// close curl resource to free up system resources 
curl_close($ch);  

Upvotes: 1

Related Questions