2013-10-20 61 views
1

我想在PHP中調用一個登錄API,如下所示,但我是使用API​​的新手。我想知道如何在這裏管理會話,以便在用戶登錄後可以調用其他API;到目前爲止,我只能夠登錄,但我無法調用任何其他API,因爲它說用戶沒有登錄。如何在用戶使用CURL登錄後調用其他API?

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://example.com/Login?username=user&password=1234"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_exec($ch); 

回答

1

你需要像這樣來存儲會話/一旦創建cookie。

function CURL_R($url, $cookie, $file, $jar) 
{ 
    $c = curl_init(); 
    curl_setopt($c, CURLOPT_URL, $url); 
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); 
    if ($file == true) { 
     curl_setopt($c, CURLOPT_COOKIEFILE, $cookie); 
    } 
    if ($jar == true) { 
     curl_setopt($c, CURLOPT_COOKIEJAR, $cookie); 
    } 
    return curl_exec($c); 
    curl_close($c); 
} 

// --- 

$username = 'username'; 
$password = 'password'; 
$cookie = $username . '.txt'; 

$login = CURL_R(
    "http://www.example.com/Login?username={$username}&password={$password}", 
    $cookie, 
    true, 
    true 
); 

$other_api = CURL_R(
    "http://www.example.com/Other-api", 
    $cookie, 
    true, 
    false 
); 

要使用CURL_R()函數的字段是URL,Cookie路徑,文件和jar。 jar是存儲cookie/session的東西,所以在登錄後jar將是錯誤的,並且文件將成爲true以在另一個API上使用cookie。

+0

傑克非常感謝你的工作,這就是我需要你的幫助,非常感謝 – user1338738

+0

沒問題的老兄很高興它的工作。 – Jake

相關問題