2011-12-30 78 views
0

我需要一些幫助翻譯以下shell腳本調用到PHPPHP JSON API客戶端調用

curl -3 --cookie /tmp/cookie --cookie-jar /tmp/cookie --insecure --data "login=login" --data "username=admin" --data "password=password" URL-HERE/login 

curl -3 --cookie /tmp/cookie --cookie-jar /tmp/cookie --insecure --data "json={'cmd':'get-data', 'id':'1'}" URL-HERE/api 

我在與第一curl命令一些困難。

得到儘可能:

$curl=curl_init(); 
    curl_setopt($curl,CURLOPT_RETURNTRANSFER ,1); 
    curl_setopt($curl,CURLOPT_HEADER , 1); 
    curl_setopt($curl,CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, FALSE); 

    curl_setopt($curl,CURLOPT_COOKIEJAR, "/tmp/cookie"); 
    curl_setopt($curl,CURLOPT_COOKIEFILE, "/tmp/cookie"); 
    curl_setopt($curl,CURLOPT_TIMEOUT,10000); 
    curl_setopt($curl,CURLOPT_URL,"URL-HERE/login"); 

    curl_setopt($curl,CURLOPT_POST ,1); 
    $post = array(
     "username" => 'admin', 
     "password" => 'password', 
     "login" => 'login', 
    ); 
    curl_setopt($curl,CURLOPT_POSTFIELDS,$post); 
    echo curl_exec($curl); 

這似乎總是呈現從URL HERE /登錄的登錄表單,並使用上述cookie的後續JSON請求似乎失敗,錯誤消息「需要是在嘗試這些請求之前登錄「。但是,上面的兩個shell命令完美無缺地工作。

我正確的想法 - 數據參數變成後變量。而JSON數據是一個名爲「json」的帖子字段,其內容已由json_encode()返回?

回答

0

你可以試試這個:(我改寫了我的一些代碼,未測試)

$url = 'URL-HERE/login'; 
$username = 'username'; 
$password = 'password'; 
$postfields = "login=login&username=$username&password=$password"; 

$cookie="/tmp/cookie"; 
$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
curl_setopt ($ch, CURLOPT_TIMEOUT, 60); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie); 
curl_setopt ($ch, CURLOPT_REFERER, $url); 
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields); 
curl_setopt ($ch, CURLOPT_POST, 1); 
$result = curl_exec ($ch); 

curl_close($ch); 
echo $result; 
+0

這工作。只要我使用相同的cookie進行後續的API調用。 – cell0 2011-12-30 14:11:57