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
  • 53,991
  • 11
  • 38
  • 52
mr.boris
  • 2,985
  • 6
  • 29
  • 57

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
  • 4,388
  • 9
  • 40
  • 77