通过PHP/Curl返回错误使用CloudFlare API

Boa*_*rdy 3 php curl cloudflare

我正在通过PHP脚本更新我的DNS.我查看了与cURL相关的API文档,所以我试图将cURL帖子转换为PHP.

我有以下代码:

$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/<MY_ZONE>/dns_records/<MY_ID>");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

    $fields = array();
    $fields["X-Auth-Email"] = "someone@mydomain.com";
    $fields["X-Auth-Key"] = "MY_KEY";
    $fields["Content-Type"] = "application/json";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $fields);

    $dnsData = array();
    $dnsData["id"] = "MY_ID";
    $dnsData["type"] = "A";
    $dnsData["name"] = "home";
    $dnsData["content"] = $newIPAddress;

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dnsData));


    echo "posting to API<br />";
    $result = curl_exec($ch);
    echo "Result: " . $result;
Run Code Online (Sandbox Code Playgroud)

通过上面的代码,我收到了来自Cloudflare的以下回复.

{"success":false,"errors":[{"code":6003,"message":"无效的请求标头","error_chain":[{"code":6100,"message":"缺少X-Auth -Email标题"},{"code":6101,"message":"缺少X-Auth-Key标头"},{"code":6105,"message":"无效的Content-Type标头,有效值是应用程序/ JSON,多部分/格式数据 "}]}]," 消息 ":[]," 结果":空}

我已经尝试将json_encode更改为http_build_query,但两者都返回相同的错误.

Alb*_*rta 7

我认为你是在滥用curl_setopt.

这是设置多个标头的正确方法:

curl_setopt($ch,CURLOPT_HTTPHEADER, ['HeaderName: HeaderValue','HeaderName2: HeaderValue2']);
Run Code Online (Sandbox Code Playgroud)

编辑

为了更清楚:

$headers = [ 
    'X-Auth-Email: someone@mydomain.com',
    'X-Auth-Key: MY_KEY',
    'Content-Type: application/json'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Run Code Online (Sandbox Code Playgroud)

标题不是键/值对,而只是值.

此外,您应该使用http_build_query()发送POST数据.