Al Amin Al Amin - 11 days ago 5
PHP Question

how to use basic authorization in php curl

i am having problem with php curl request with basic authorization.
here is the command line curl

curl -H "Accept: application/product+xml" "https://{id}:{api_key}@api.domain.com/products?limit=1&offset=0"


i have tried by setting curl header in following ways but it's not wroking

Authorization: Basic id:api_key
or
Authorization: Basic {id}:{api_key}


but it's not working, i got response "authentication parameter in the request are missing or invalid" but i have used proper id and api_key which is working in command line curl(i tested)

please help me.

Regards

Al Amin

Answer

Try the following code :

$username='ABC';
$password='XYZ';
$URL='<URL>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);