我正在通过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;
通过上面的代码,我收到了来自Cloudflare的以下回复.
{“success”:false,”errors”:[{“code”:6003,”message”:”Invalid request
headers”,”error_chain”:[{“code”:6100,”message”:”Missing X-Auth-Email
header”},{“code”:6101,”message”:”Missing X-Auth-Key
header”},{“code”:6105,”message”:”Invalid Content-Type header, valid
values are
application/json,multipart/form-data”}]}],”messages”:[],”result”:null}
我已经尝试将json_encode更改为http_build_query,但两者都返回相同的错误.
解决方法:
我认为你是在滥用curl_setopt.
这是设置多个标头的正确方法:
curl_setopt($ch,CURLOPT_HTTPHEADER, ['HeaderName: HeaderValue','HeaderName2: HeaderValue2']);
编辑
为了更清楚:
$headers = [
'X-Auth-Email: someone@mydomain.com',
'X-Auth-Key: MY_KEY',
'Content-Type: application/json'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
标题不是键/值对,而只是值.
此外,您应该使用http_build_query()发送POST数据.