使用PHP发送身份验证标头

时间:2014-11-07 22:40:11

标签: php xml api

我是API的新手,但我需要发送一个身份验证标头,其中包含我对XML数据文件的请求。

我有以下脚本在返回时处理XML文件

<?php
$xml=simplexml_load_file("https://api.familysearch.org/reservation/v1/person/L81G-M81") or die("Error: Cannot create object");

print_r($xml->persons->person->baptism);
?> 

唯一的问题是它返回状态代码401 Unauthenticated to my request。

有人可以告诉我如何使用我的请求发送身份验证标头吗?我正在使用访问令牌进行身份验证。同样,我是使用API​​的新手,并希望得到帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用curl发送类似这样的标题:

$service_url = 'https://api.familysearch.org/reservation/v1/person/L81G-M81';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password"); //Your credentials here
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);

$curl_res = curl_exec($curl);
$response = json_decode($curl_res);
curl_close($curl);

var_dump($response);

确认您已为ssl连接启用了openssl模块。

修改

通过此处发送包含令牌的标头是一个OAuth示例。

$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: OAuth '.$accesstoken;

curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);

要测试命令,可以使用命令行:

curl -H "Authorization: Bearer <ACCESS_TOKEN>" http://www.example.com