PHP Curl设置apikey问题

时间:2018-06-23 14:09:57

标签: php curl post request php-curl

我想用PHP Curl发出POST请求,但找不到相关示例。

这是一个Curl请求,可以在我的终端上正常工作

curl -X POST -u "apikey:*********" --form "images_file=@filename.jpg" "www.example.com/api"

那么,如何通过PHP Curl发出相同的请求?

这是我的示例:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,'www.example.com/api');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Authorization: ' . $apiKey
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

var_dump($server_output);

这不起作用:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'apikey:*******'
));

这也不是:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  '*******'
));

结果,我有这个:

string(37) "{"code":401, "error": "Unauthorized"}"

1 个答案:

答案 0 :(得分:1)

尝试使用CURLOPT_USERPWD:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);