curl_setopt():您必须使用CURLOPT_HTTPHEADER参数传递对象或数组

时间:2016-06-15 06:25:37

标签: php curl php-curl

我的代码:

private static $API_ACCESS_KEY = 'AIzaSyDG3fYAj1uW7VB-wejaMJyJXiO5JagAsYI';
$headers = array(
            'Authorization: key=' .self::$API_ACCESS_KEY,
            'Content-Type: application/json');

private function useCurl(&$model, $url, $headers, $fields = null) {
            // Open connection
                $ch = curl_init();
            if ($url) {
                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Disabling SSL Certificate support temporarly
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            if ($fields) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            }

            // Execute post
            $result = curl_exec($ch);
            if ($result === FALSE) {
                die('Curl failed: ' . curl_error($ch));
            }

            // Close connection
            curl_close($ch);

            return $result;
    }
}

错误:

  

curl_setopt():您必须使用CURLOPT_HTTPHEADER参数传递对象或数组

1 个答案:

答案 0 :(得分:0)

$ header根本不是arary。确保它是一个数组,如果不是则抛出InvalidArgumentException。像这样:

private function useCurl(&$model, $url, $headers, $fields = null) {
if(!is_array($headers)){throw new InvalidArgumentException('headers MUST be an array!');}
...

或者,从PHP7开始,

private function useCurl(&$model, $url, array $headers, $fields = null) {
...

并注意,当您在上面声明一个名为$ headers的变量时,它在函数定义之外,因此在函数范围之外。函数的$ headers是输入参数#3