2017-08-28 120 views
1

我想創建一個CURL來獲得auth tokken。如何在PHP中使用數據和標題進行CURL POST

平臺開發論壇給我說:

curl -X POST \ 
    --header 'Content-Type: application/json; charset=utf-8' \ 
    --header 'Accept: application/json' \ 
    -d '{"email":"MY_EMAIL","password":"MY_PASSWORD"}' \ 
    'https://api.voluum.com/auth/session' 

如何使在PHP中的工作?

+0

你連做任何研究嗎? http://php.net/manual/en/book.curl.php –

+0

@SebastianTkaczyk是的,但我不明白怎麼做:/ –

回答

0

你可以像下面: -

<?php                
$data_string = '{"email":"MY_EMAIL","password":"MY_PASSWORD"}';                     

$ch = curl_init('https://api.voluum.com/auth/session');                  
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                  
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                  
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                   
    'Content-Type: application/json; charset=utf-8', 
    'Accept: application/json' 
));                             

$result = curl_exec($ch); 
if (curl_errno($ch)) { 
    echo 'Error:' . curl_error($ch); 
    exit; 
} 
curl_close ($ch); 
var_dump($result); 

我運行它,並低於響應發現(因爲我沒有郵件的ID和密碼): - https://prnt.sc/gdz82r

但令人愉快的部分是代碼成功執行當你將提供正確的憑證,那麼它會給你正確的輸出。

1

試試這個:https://incarnate.github.io/curl-to-php/

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/ 
$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, "https://api.voluum.com/auth/session"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"email\":\"MY_EMAIL\",\"password\":\"MY_PASSWORD\"}"); 
curl_setopt($ch, CURLOPT_POST, 1); 

$headers = array(); 
$headers[] = "Content-Type: application/json; charset=utf-8"; 
$headers[] = "Accept: application/json"; 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$result = curl_exec($ch); 
if (curl_errno($ch)) { 
    echo 'Error:' . curl_error($ch); 
} 
curl_close ($ch); 
+0

這個也是正確的。+ 1 –

1
$vars = '{"email":"MY_EMAIL","password":"MY_PASSWORD"}'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,"https://api.voluum.com/auth/session"); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

$headers = ['Content-Type: application/json; charset=utf-8', 
'Accept: application/json']; 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$server_output = curl_exec($ch); 
if (curl_errno($ch)) { 
    echo 'Error:' . curl_error($ch); 
    exit; 
} 
curl_close ($ch); 

print_r($server_output); 
+0

它也是正確的。+ 1 –