-1

My code:

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;
    }
}

Error:

curl_setopt(): You must pass either an object or an array with the CURLOPT_HTTPHEADER argument

zondo
  • 19,901
  • 8
  • 44
  • 83
Vinupriya
  • 1
  • 1
  • 1
  • 2
  • Try to print the value of `$headers` by using `print_r($headers);` and add the output of the print statement inside your comments, to clarify your question. – Nagama Inamdar Jun 15 '16 at 07:58
  • $headers = array( 'Authorization: key=' .self::$API_ACCESS_KEY, 'Content-Type: application/json' ); print_r($headers); Answer is :Array ( [0] => Authorization: key=AIzaSyDG3fYAj1uW7VB-wejaMJyJXiO5JagAsYI [1] => Content-Type: application/json ) – Vinupriya Jun 15 '16 at 09:34

1 Answers1

0

$headers is simply not an arary. make sure it's an array, and throw an InvalidArgumentException if its not. like this:

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

or, as of PHP7,

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

and note that while you declare a variable called $headers right above, its outside the function definition, and thus outside of the function's scope. the function's $headers is input argument #3

hanshenrik
  • 19,904
  • 4
  • 43
  • 89