如何将CURL命令转换为PHP?

时间:2020-04-12 15:21:58

标签: php curl

你好,我在CURL中有命令

jQuery(document).ready(function refreshStats(){
    jQuery("#stats").load("https://domain/stats.php");
    setTimeout(refreshStats, 50000);
});

返回

curl –k –H "Content-Type:application/json" –d "{\"api_key\":\"123456789\"}" –X GET "https://1.1.1.1:7777/auth"

如何在php中转换此命令?

{"Token":"ABC123"}

我尝试了此方法,但不起作用

2 个答案:

答案 0 :(得分:1)

要使CURL正常工作,您需要先初始化会话,以便:

$ch = curl_init("https://1.1.1.1:7777/auth");
/*CURL OPTIONS*/
$result = curl_exec($ch);
echo $result;

如果您将api密钥作为post参数传递,则curl选项应该类似于:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode(['api_key'=>"123456789"]));
curl_setopt($ch, CURLOPT_HTTPHEADER,['Content-Type: application/json']);

答案 1 :(得分:0)

这是解决方案:

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
  $headers = array();
  $headers[] = 'Content-Type: application/json';
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['api_key'=>"123456789"]));
相关问题