php - 未设置 PHP Curl 标头
问题描述
我正在尝试为 curl 标头设置 2 个变量,但似乎看不出有什么问题。我在 php 日志中没有收到任何错误,但是当我打印出 curl 信息时,我可以看到没有设置标题。朝着正确方向的任何一点都会有所帮助。谢谢
我正在使用 PHP cURL 自定义标头的示例
class GetAuctions
{
private $APIKeyID = "theIDhere";
private $APIKeyPass = "thePasswordHere";
private $BaseURL = "https://someurlHere";
public function __construct()
{
//get list of upcoming auctions
$get_data = $this->callAPI('GET', $this->BaseURL, false);
//turn the response into a json
$response = json_decode($get_data, true);
//display the response for testing
echo print_r($response);
$errors = $response['response']['errors'];
$data = $response['response']['data'][0];
echo print_r($data);
}
function callAPI($method, $url, $data){
$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
$headers =array();
$headers['apiKeyID'] = $this->APIKeyID;
$headers['apiKeyPass'] = $this->APIKeyPass;
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
echo "<br/>";
echo print_r(curl_getinfo($curl));
echo "<br/>";
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
}
我也试过这个:
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"apiKeyID: $this->APIKeyID",
"apiKeyPass: $this->APIKeyPass"
));
我的回复如下所示:
Array ( [url] => https://MyURLHere [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0 [namelookup_time] => 0 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [redirect_url] => [primary_ip] => [certinfo] => Array ( ) [primary_port] => 0 [local_ip] => [local_port] => 0 ) 1
连接失败
解决方案
看起来您的标题格式不正确:
"apiKeyID : $this->APIKeyID",
您应该删除冒号前的空格:
"apiKeyID: ${this->APIKeyID}",
顺便说一句:出于调试目的,您还可以使用CURLOPT_VERBOSE来查看 cURL 发送的内容。如果您无法在运行时查看 stderr,请将其重定向到文件:
curl_setopt($c, CURLOPT_STDERR, fopen('curl-log.txt', 'w+'));
推荐阅读
- jquery - 用 jquery 填充 html 表数据失败 Uncaught ReferenceError
- javascript - 如何使用引导程序 4 警报?
- elasticsearch - 如何将 ElasticSearch 命令翻译成 NEST 并使其具有幂等性
- stata - 面板数据中的返回计算不正确
- http - Jira 资源因 net::ERR_CONNECTION_ABORTED 而失败
- html - HTML 表格:Slicky 标题和最后一列自动宽度
- sql - SQL Server - 存储过程 - 二进制搜索算法
- java - 哪些应用服务器支持 WAR 中的多版本 JAR(如果有)?
- javascript - 防止“showOpenDialog”添加最近的文档条目
- azure - Azure B2C 禁用 SignUpAndSignIn 策略的注册