2012-03-03 112 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