Using CURL with PHP to send POST field data using http header Authentication

October 6, 2016

Okay, so until now I had been using api keys passed through the post fields but on a more recent project I was asked to send the api key through the headers when making the request, so I have made myself a little function to use curl and pass the api key through CURLOPT_HTTPHEADER.

function my_curl_request($postfields) {
 
     //define the end point url and api key
     $api_end_point_url = "https://some_end_point_url.com/api/"
     $api_key = "ABC123";
	
	//urlify the data for the POST
	$fields_string = http_build_query($postfields);
 
 	//prepare curl request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_end_point_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [$api_key]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
	curl_setopt($ch, CURLOPT_POST, count($postfields));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
	
    //needed for https
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	
	//make the request
    $result = curl_exec($ch);

    curl_close($ch);
 
	return $result;
 
}

This will be the call to your curl function and you can print out the results of the call.

//define the data to send to the api
$postfields = array(
   'first_name' => "Joe",
   'last_name' => "Bloggs",
);

//make the request to the api.
$result = my_curl_request($postfields);

//echo results
echo $result;