0

I have the following post api request, the example provided was using cURL command:

curl "https://muserver.com/api/gettoken" --request POST --include -
-header "Content-Type: application/json" --user test:test

I am trying to perform this request using cURL in PHP but getting authentication error.

following is what I have tried:

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

I think I should pass the user and pass. in the form of

--user test:test

but really don't know how to do it.

Fshamri
  • 1,346
  • 4
  • 17
  • 32

2 Answers2

1

You seem to be lacking the $username and $password variables :

$username='test';
$password='test';

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);
Calimero
  • 4,238
  • 1
  • 23
  • 34
0
<?php


$url_simple_auth = 'https://www.some_url_need_basic_auth_first.com';
$url_download = 'https://www.some_url_need_basic_auth_first.com/dowonload_file.zip';
$username = 'some_login';
$password = 'some_pass';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_simple_auth);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// login simple auth
$simple_auth = curl_exec($ch);

// download file
curl_setopt($ch, CURLOPT_REFERER, $url_simple_auth);
curl_setopt($ch, CURLOPT_URL, $url_download);
curl_setopt ($ch, CURLOPT_POST, 1); 
curl_setopt ($ch, CURLOPT_POSTFIELDS, "email=$username&key=$password"); 
$result = curl_exec($ch);

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($status_code);
var_dump($result);