如何在PHP curl中使用基本授权

时间:2013-11-19 05:58:35

标签: php curl authorization

我在使用基本授权的PHP卷曲请求时遇到问题。

这是命令行curl:

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

我试过通过以下方式设置curl标头,但它不起作用

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

我得到响应“请求中的身份验证参数丢失或无效”但我使用了正确的id和api_key,它在命令行curl中工作(我测试过)

请帮帮我。

4 个答案:

答案 0 :(得分:122)

请尝试以下代码:

$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);

答案 1 :(得分:6)

你能试试吗,

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

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

答案 2 :(得分:2)

$headers = array(
    'Authorization: Basic '. base64_encode($username.':'.$password),
);
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

答案 3 :(得分:0)

通过标头的简单方法

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);
curl_close($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