繁体   English   中英

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

[英]Send HTTP post request with http basic auth in PHP

我有以下post 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);

我想我应该通过用户并通过。 以...的形式

-用户测试:测试

但真的不知道该怎么做。

您似乎缺少$ 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);
<?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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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