如何使用PHP curl使用HTTP基本身份验证发出请求?

时间:2010-01-26 15:42:19

标签: php rest curl basic-authentication

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

如何使用curl进行身份验证(http basic)请求?我是否必须自己添加标题?

11 个答案:

答案 0 :(得分:343)

你想要这个:

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

答案 1 :(得分:104)

CURLOPT_USERPWD基本上使用http标头发送user:password字符串的base64,如下所示:

Authorization: Basic dXNlcjpwYXNzd29yZA==

除了CURLOPT_USERPWD之外,你还可以使用HTTP-Request标题选项以及下面的其他标题:

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

答案 2 :(得分:33)

直接使用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);

答案 3 :(得分:7)

与SOAP不同,REST不是标准化协议,因此拥有“REST客户端”有点困难。但是,由于大多数RESTful服务使用HTTP作为其底层协议,因此您应该能够使用任何HTTP库。除了cURL之外,PHP还有以下PEAR:

HTTP_Request2

取代了

HTTP_Request

他们如何进行HTTP Basic Auth

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

还支持Digest Auth

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

答案 4 :(得分:4)

Yahoo有一个使用PHP调用REST服务的教程:

Make Yahoo! Web Service REST Calls with PHP

我自己并没有使用它,但雅虎是雅虎,应该保证至少达到某种程度的质量。但它们似乎不包括PUT和DELETE请求。

此外,User Contributed Notes to curl_exec()和其他人包含大量有用信息。

答案 5 :(得分:3)

迈克尔道林非常积极地保持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']]);

the docs

答案 6 :(得分:3)

如果授权类型是Basic auth,发布的数据是json,那么就这样做

field_id

答案 7 :(得分:0)

对于那些不想使用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);

答案 8 :(得分:0)

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

答案 9 :(得分:0)

使用基本方法的其他方法是:

$curl = curl_init();

$public_key = "public_key";
$private_key = "private_key";

curl_setopt_array($curl, array(
CURLOPT_URL => "https://url.endpoint.co/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"Authorization: Basic ".base64_encode($public_key.":".$private_key)
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

答案 10 :(得分:-6)

有多个REST框架。我强烈建议调查Slim mini Framework for PHP Here是其他人的列表。