如何用curl php维护会话?

时间:2017-02-24 12:00:02

标签: php session curl

我知道在Stack-overflow之前已经多次询问过这个问题,但没有一个答案解决了我的问题。

我正在编写一个使用curl远程浏览JSP站点的php脚本: 这是我的代码:

<?php
$loginUrl = 'http://ccc.hyundai-motor.com/servlet/ccc.login.CccLoginServlet';

 $sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SHARE, $sh);
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'the post data including my username and password and other hidden fields');
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_SHARE, $sh);
curl_setopt($ch2, CURLOPT_URL,'http://ccc.hyundai-motor.com/servlet/ccc/admin/user/UserInfoServlet?cmd=myUserInfo');
curl_setopt($ch2, CURLOPT_COOKIEFILE,'cookie.txt');
curl_setopt($ch2, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch2, CURLOPT_VERBOSE, true);
$result = curl_exec($ch2);  
print $result;
curl_share_close($sh);
curl_close($ch);
curl_close($ch2);
?>

当我执行代码时,会创建cookie文件,但是我收到错误&#34;会话丢失,请重新登录&#34;。

1 个答案:

答案 0 :(得分:0)

您需要通过curl_share_init创建句柄并将其传递给每个cURL实例,否则实例将单独存在,并且无法共享所需的会话cookie。

PHP手册中的一个例子:

// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
相关问题