Home » Php » How to use basic authorization in PHP curl

How to use basic authorization in PHP curl

Posted by: admin April 23, 2020 Leave a comment


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 working

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

I get the 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.

How to&Answers:

Try the following code :


$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_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);


Can you try this,

 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  

REF: http://php.net/manual/en/function.curl-setopt.php


Its Simple Way To Pass Header

function get_data($url) {

$ch = curl_init();
$timeout = 5;
$username = 'c4f727b9646045e58508b20ac08229e6';        // Put Username 
$password = '';                                        // Put Password
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");    // Add This Line
$data = curl_exec($ch);
return $data;
$url = "https://storage.scrapinghub.com/items/397187/2/127";
$data = get_data($url);
echo '<pre>';`print_r($data_json);`die;    // For Print Value

Check My JSON Value