首页 > 解决方案 > 未设置 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

连接失败

标签: phpcurlheader

解决方案


看起来您的标题格式不正确:

"apiKeyID : $this->APIKeyID",

您应该删除冒号前的空格:

"apiKeyID: ${this->APIKeyID}",

顺便说一句:出于调试目的,您还可以使用CURLOPT_VERBOSE来查看 cURL 发送的内容。如果您无法在运行时查看 stderr,请将其重定向到文件:

curl_setopt($c, CURLOPT_STDERR, fopen('curl-log.txt', 'w+'));

推荐阅读