如何使用带有 PHP curl 的 HTTP 基本身份验证发出请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2140419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make a request using HTTP basic authentication with PHP curl?
提问by blank
I'm building a REST web service client in PHP and at the moment I'm using curl to make requests to the service.
我正在用 PHP 构建一个 REST Web 服务客户端,目前我正在使用 curl 向服务发出请求。
How do I use curl to make authenticated (http basic) requests? Do I have to add the headers myself?
如何使用 curl 发出经过身份验证的(http 基本)请求?我必须自己添加标题吗?
回答by mr-sk
You want this:
你要这个:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Zend has a REST client and zend_http_client and I'm sure PEAR has some sort of wrapper. But its easy enough to do on your own.
Zend 有一个 REST 客户端和 zend_http_client,我确信 PEAR 有某种包装器。但它很容易自己做。
So the entire request might look something like this:
所以整个请求可能看起来像这样:
$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
curl_close($ch);
回答by Sabuj Hassan
CURLOPT_USERPWDbasically sends the base64 of the user:passwordstring with http header like below:
CURLOPT_USERPWD基本上发送user:password带有 http 标头的字符串的 base64,如下所示:
Authorization: Basic dXNlcjpwYXNzd29yZA==
So apart from the CURLOPT_USERPWDyou can also use the HTTP-Requestheader option as well like below with other headers:
所以除了CURLOPT_USERPWD你还可以使用HTTP-Requestheader 选项以及下面的其他标题:
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("user:password") // <---
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
回答by Fedir RYKHTIK
The most simple and native way it's to use CURL directly.
最简单和原生的方式是直接使用 CURL。
This works for me :
这对我有用:
<?php
$login = 'login';
$password = 'password';
$url = 'http://your.url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
$result = curl_exec($ch);
curl_close($ch);
echo($result);
回答by nategood
Unlike SOAP, REST isn't a standardized protocol so it's a bit difficult to have a "REST Client". However, since most RESTful services use HTTP as their underlying protocol, you should be able to use any HTTP library. In addition to cURL, PHP has these via PEAR:
与 SOAP 不同,REST 不是标准化协议,因此拥有“REST 客户端”有点困难。但是,由于大多数 RESTful 服务使用 HTTP 作为其底层协议,因此您应该能够使用任何 HTTP 库。除了 cURL,PHP 还通过 PEAR 提供了这些:
which replaced
哪个取代了
A sample of how they do HTTP Basic Auth
他们如何进行 HTTP 基本身份验证的示例
// This will set credentials for basic auth
$request = new HTTP_Request2('http://user:[email protected]/secret/');
The also support Digest Auth
也支持 Digest Auth
// This will set credentials for Digest auth
$request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);
回答by Sunny Vashisht
If the authorization type is Basic auth and data posted is json then do like this
如果授权类型是 Basic auth 并且发布的数据是 json 然后这样做
<?php
$data = array("username" => "test"); // data u want to post
$data_string = json_encode($data);
$api_key = "your_api_key";
$password = "xxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json')
);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
$errors = curl_error($ch);
$result = curl_exec($ch);
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $returnCode;
var_dump($errors);
print_r(json_decode($result, true));
回答by Pekka
Yahoo has a tutorial on making calls to their REST services using PHP:
雅虎有一个使用 PHP 调用 REST 服务的教程:
Make Yahoo! Web Service REST Calls with PHP
I have not used it myself, but Yahoo is Yahoo and should guarantee for at least some level of quality. They don't seem to cover PUT and DELETE requests, though.
我自己没有使用过它,但雅虎是雅虎,至少应该保证一定程度的质量。不过,它们似乎没有涵盖 PUT 和 DELETE 请求。
Also, the User Contributed Notes to curl_exec()and others contain lots of good information.
此外,用户对 curl_exec()和其他人的贡献注释包含很多很好的信息。
回答by Wouter
For those who don't want to use curl:
对于那些不想使用 curl 的人:
//url
$url = 'some_url';
//Credentials
$client_id = "";
$client_pass= "";
//HTTP options
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array ('Content-type: application/json', 'Authorization: Basic '.base64_encode("$client_id:$client_pass")),
'content' => "some_content"
)
);
//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
if(json_last_error() != JSON_ERROR_NONE){
return null;
}
print_r($result);
回答by Serhii Andriichuk
You just need to specify CURLOPT_HTTPAUTH and CURLOPT_USERPWD options:
你只需要指定 CURLOPT_HTTPAUTH 和 CURLOPT_USERPWD 选项:
$curlHandler = curl_init();
$userName = 'postman';
$password = 'password';
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/basic-auth',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $userName . ':' . $password,
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
Or specify header:
或指定标题:
$curlSecondHandler = curl_init();
curl_setopt_array($curlSecondHandler, [
CURLOPT_URL => 'https://postman-echo.com/basic-auth',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . base64_encode($userName . ':' . $password)
],
]);
$response = curl_exec($curlSecondHandler);
curl_close($curlSecondHandler);
Guzzle example:
狂饮示例:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$userName = 'postman';
$password = 'password';
$httpClient = new Client();
$response = $httpClient->get(
'https://postman-echo.com/basic-auth',
[
RequestOptions::AUTH => [$userName, $password]
]
);
print_r($response->getBody()->getContents());
See https://github.com/andriichuk/php-curl-cookbook#basic-auth
回答by Jannie Theunissen
Michael Dowling's very actively maintained Guzzleis a good way to go. Apart from the elegant interface, asynchronous calling and PSR compliance, it makes the authentication headers for REST calls dead simple:
Michael Dowling 非常积极地维护Guzzle是一个很好的方法。除了优雅的界面、异步调用和 PSR 合规性之外,它还使 REST 调用的身份验证标头变得非常简单:
// Create a client with a base URL
$client = new GuzzleHttp\Client(['base_url' => 'http://myservices.io']);
// Send a request to http://myservices.io/status with basic authentication
$response = $client->get('/status', ['auth' => ['username', 'password']]);
See the docs.
请参阅文档。
回答by rudder
There are multiple REST frameworks out there. I would strongly recommend looking into Slim mini Framework for PHP
Hereis a list of others.
有多个 REST 框架。我强烈建议您查看适用于 PHP 的 Slim mini Framework,
这是其他的列表。

