我正在通过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);
我该如何维护浏览器会话......
答案 0 :(得分: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);
答案 1 :(得分: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并在下一个请求中附加到有效的标题中。