2017-02-24 127 views
0

我知道這個問題在堆棧溢出之前已經被問了很多次,但是沒有任何答案能夠解決我的問題。如何保持與curl php的會話?

我寫一個使用捲曲遠程瀏覽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文件中的代碼,但我得到一個錯誤「會話丟失請重新登錄「。

+0

http://stackoverflow.com/questions/13020404/keeping-session-alive-with-curl-and-php#13020494 – JustOnUnderMillions

+0

我已經讀了以前的問題,但沒有新的東西,你可以更具體的關於我的代碼問題? –

+0

事情你應該只在第一個調用中使用這些'CURLOPT_COOKIEJAR | CURLOPT_COOKIEFILE''CURLOPT_COOKIEJAR'並且在第二部分使用'CURLOPT_COOKIEFILE' http://stackoverflow.com/a/13020460/4916265 – JustOnUnderMillions

回答

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); 
+0

我試過了,正如你所說的那樣,但是它仍然給出同樣的錯誤,我已經更新了相應的代碼,請看看。 –