使用PHP基本身份验证发送HTTP发布请求

时间:2017-09-16 13:10:44

标签: php api curl basic-authentication

我有以下后api请求,提供的示例是使用cURL命令:

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

我正在尝试使用PHP中的cURL执行此请求但是出现身份验证错误。

以下是我的尝试:

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

我想我应该通过用户传递。以

的形式
  

- 用户测试:测试

但真的不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

您似乎缺少$ username和$ password变量:

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

答案 1 :(得分: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);
相关问题