简体   繁体   中英

Send HTTP post request with http basic auth in PHP

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM