2012-03-03 84 views
0

我正在通过php向另一个域发送CURL获取请求以获取json值,但是因为我知道curl使用临时会话,但我如何维护卷发请求中的所有浏览器会话?这里是我的代码使用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); 

我如何保持浏览器会话...

+0

浏览器会话是什么意思?调用此脚本时使用的会话? – 2012-03-03 08:21:49

+0

是的,因为当我打电话给json请求时,它应该有我正在... – 2012-03-03 08:42:18

回答

0
 $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并在接下来的请求连接到该作品的标题。

1

可以使用CURLOPT_COOKIEJAR选项(参见documentation)到所有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); 
+0

的会话,但它只能保存当前浏览器? – 2012-03-03 08:38:00

+0

@ user1245078我不确定你的意思,你担心cookies不会被其他访客重复使用吗?如果您将Cookie存储在jar中,则即使在脚本的不同执行中,也可以重用它们。 – 2012-03-03 08:41:22

+0

ohk你有任何特定的代码来执行它吗? – 2012-03-03 08:45:07