如何在PHP中使用数据和标题进行CURL POST

问题描述:

我想创建一个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是的,但我不明白怎么做:/ –

你可以像下面: -

<?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

但令人愉快的部分是代码成功执行当你将提供正确的凭证,那么它会给你正确的输出。

试试这个: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 –

$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 –