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

时间:2022-09-06 12:05:19

I am having problem with PHP curl request with basic authorization.

我有基本授权的PHP卷曲请求有问题。

Here is the command line curl:

这是命令行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

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

Authorization: Basic id:api_key
or 
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)

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

Please help me.

请帮帮我。

2 个解决方案

#1


111  

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

#2


5  

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

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

#1


111  

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

#2


5  

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

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