使用CURL维护浏览器会话的跨域


Cross domain for maintaining browser session using CURL

我正在通过php向另一个域发出CURL get请求以获取json值,但我知道CURL使用临时会话,但我如何在CURL请求中维护所有浏览器会话?这是我的代码

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

如何维护浏览器会话。。。

您可以使用CURLOPT_COOKIEJAR选项(请参阅文档)将所有cookie保存到一个文件中。您可以在以后使用CURLOPT_COOKIEFILE选项导入此文件,这将发送存储在指定jar中的所有cookie。

基于代码的在脚本执行之间保持持久会话的示例:

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

为此,您需要存储cookie,并在下一个请求中附加到有效的头中。