如何在PHP中使用数据和标头发布CURL

时间:2017-08-28 11:11:41

标签: php curl

我想制作一个CURL来获得认证。

平台开发论坛告诉我:

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中完成这项工作?

3 个答案:

答案 0 :(得分: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);

答案 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);

答案 2 :(得分: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

但令人愉快的部分 是代码 已成功执行 ,当您提供正确的凭据时,它会给出你纠正输出。