0

I want to make POST request with PHP Curl but can't find relevant examples.

This is a Curl request which works fine in my terminal:

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

So, how to make the same request via PHP Curl?

This is my sample:

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

This doesn't work:

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

Neither does this:

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

As a result I have this:

string(37) "{"code":401, "error": "Unauthorized"}"
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
mr.boris
  • 3,667
  • 8
  • 37
  • 70

1 Answers1

1

Try this w/ 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);
koalaok
  • 5,075
  • 11
  • 47
  • 91