cURL header in PHP

BR
BR used Ask the Experts™
on
How can I add this to my existing header?

$header = "Authorization: Basic " . base64_encode($ClientID . ':' . $ClientSecret);

My code is like below. And I need to add it to my header. Thank you

<?php

$ClientID = "myclientid";

$ClientSecret = "myclientsecret";

$url = 'https://mysitelink...';


//create a new cURL resource
$ch = curl_init($url);

//setup request to send json via POST
$data = array(
    'username' => 'myusername',
    'password' => 'mypassword',
);

$nkolay = json_encode(array($data));

//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $nkolay);

//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));


//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute the POST request
$result = curl_exec($ch);

//burada linkteki sayfadan datayı alıyorum. 
var_dump($result);

//close cURL resource
curl_close($ch);

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
just add it to the array of CURLOPT_HTTPHEADERs line 25

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json',"Authorization: Basic " . base64_encode($ClientID . ':' . $ClientSecret)));
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
I would do it like this
$headers = [
  'Content-Type:application/json',
  'Authorization: Basic ' . base64_encode("{$ClientID}:{$ClientSecret}")
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Open in new window

There is much to be said for neat layout and code clarity.
BRDigital Marketing

Author

Commented:
thank you both
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Commented:
By the way, this is what the CURLOPT_USERPWD option does for you (base64-encodes the content and adds it to the headers). Usage:

curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $password);
BRDigital Marketing

Author

Commented:
Thank you so much @gr8gonzo
also note that you can do the same thing without curl using a regular stream_get_contents with proper context options
http://php.net/manual/en/context.http.php

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial