[英]HTTP Basic Authentication cURL using PHP
我試圖使用HTTP基本身份驗證從API中提取數據。 對API的HTTP請求受HTTP基本身份驗證保護。 HTTP基本身份驗證由令牌和密鑰組成。
我嘗試了很多不同的技術,但不斷得到沒有提供身份驗證的響應。 我不確定令牌:secret方法是否與用戶名:密碼不同但我無法通過身份驗證進行驗證。
stdClass對象([error_message] =>未提供身份驗證。)
這是API文檔 - https://www.whatconverts.com/api/
<?php
$token = "xxx";
$secret = "yyy";
$response = get_web_page("https://leads.seekmomentum.com/api/v1/leads");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
CURLOPT_HTTPAUTH => "CURLAUTH_BASIC", // authentication method
CURLOPT_USERPWD => "$token:$secret", // authentication
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
這是錯的:
CURLOPT_HTTPAUTH => "CURLAUTH_BASIC", // authentication method
^^^^^^^^^^^^^^^^
這是一個字符串,而不是卷曲常量。 嘗試
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, // authentication method
代替。
它的區別在於:
define('FOO', 'bar');
echo FOO // outputs bar
echo "FOO" // outputs FOO
您需要將全局變量傳遞到本地范圍。 去做這個...
更改:
function get_web_page($url) {
至:
function get_web_page( $url, $token, $secret ) {
並改變:
$response = get_web_page("https://leads.seekmomentum.com/api/v1/leads");
至:
$response = get_web_page( "https://leads.seekmomentum.com/api/v1/leads", $token, $secret );
和:
刪除CURLAUTH_BASIC周圍的引號 - 它是常量,而不是值。 (帽子提示@iainn)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.