如何使用HTTP基本认证和PHP curl发出请求?


225

我正在用PHP构建一个REST Web服务客户端,此刻我正在使用curl向服务发出请求。

如何使用curl发出经过身份验证的请求(http基本)?我必须自己添加标题吗?

Answers:


392

你要这个:

curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  

Zend有一个REST客户端和zend_http_client,我敢肯定PEAR有某种包装。但是它很容易自己完成。

因此,整个请求可能如下所示:

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

这样效果更好,然后分别设置用户和密码
Kit Ramos

125

CURLOPT_USERPWD基本发送user:password带有http头的字符串的base64,如下所示:

Authorization: Basic dXNlcjpwYXNzd29yZA==

因此,除了之外,CURLOPT_USERPWD您还可以将HTTP-Requestheader选项与以下其他headers一起使用:

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("user:password") // <---
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

这种传递自定义auth标头而不是CURLOPT_USERPWD对我有用的方法。
aalaap

40

直接使用CURL的最简单和本机的方式。

这对我有用:

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

7

与SOAP不同,REST不是标准协议,因此拥有“ REST Client”有点困难。但是,由于大多数RESTful服务都使用HTTP作为其基础协议,因此您应该能够使用任何HTTP库。除了cURL,PHP还通过PEAR提供了这些功能:

HTTP_Request2

取代了

HTTP_Request

他们如何进行HTTP基本身份验证的示例

// This will set credentials for basic auth
$request = new HTTP_Request2('http://user:password@www.example.com/secret/');

还支持摘要身份验证

// This will set credentials for Digest auth
$request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);

通过REST客户端,我的意思是抽象出一些将curl用于http get,post,put,delete等的底层细节。这是我通过构建自己的php类来完成的工作;我想知道是否有人已经这样做了。
空白

1
是的,那么您可能会对HTTP_Request_2感兴趣。它摘录了PHP中最丑陋的cUrl。要设置您使用的方法,请使用setMethod(HTTP_Request2 :: METHOD_ *)。使用PUT和POST,只需设置setBody(<<您的xml,json等表示形式在这里>>)即可设置请求的正文。上述认证。它还具有HTTP响应的抽象(cUrl真正缺少的东西)。
nategood 2010年

6

如果授权类型为“基本身份验证”,发布的数据为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));


4

您只需要指定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);

或指定标题:

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

枪口的例子:

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

参见https://github.com/andriichuk/php-curl-cookbook#basic-auth


3

迈克尔·道林(Michael Dowling)非常积极地维护着“ 枪口”是一个不错的选择。除了优美的界面,异步调用和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']]);

请参阅文档


3

对于那些不想使用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 using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.