簡體   English   中英

為什么 PHP 腳本中沒有執行 curl 代碼? (WAMP 服務器)

[英]Why is the curl code not executed in PHP script? (WAMP Server)

我正在嘗試獲取令牌以使用 Microsoft Graph API ( https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest- 1.0 ) 通過 Curl。 我用這個 function 設置了一個簡單的 Php 文件:

function getToken() {
echo "start gettoken";
var_dump(extension_loaded('curl'));
$jsonStr = http_build_query(Array(
    "client_id" => "***",
    "scope" => "https://graph.microsoft.com/.default",
    "client_secret" => "***",
    "grant_type" => "client_credentials"
));
$headers = Array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($jsonStr));

$ch = curl_init("https://login.microsoftonline.com/***.onmicrosoft.com/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$token = curl_exec($ch);
echo "test after curl";

return $token;

curl_error($ch);

 }

但是,我想知道為什么 curl 請求不起作用。 curl 代碼塊之后的回聲也沒有被執行,而 'start gettoken' 是。 我的 WAMP 中啟用了 PHP_curl。 為什么是這樣?

您確定 CURL 已啟用嗎,因為您發布的代碼沒有問題,並且在執行 curl 之前和之后給出回顯響應。

您正在以 JSON 格式發送令牌請求,然后您在向服務器撒謊說它是application/x-www-form-urlencoded -encoded,而實際上它是application/json -encoded,因為這兩種格式是完全不兼容,服務器無法解析它。 並且...理想情況下,它應該響應HTTP 400 bad request (因為您的請求無法解析為 x-www-form-urlencoded)

無論如何,要以application/x-www-form-urlencoded格式實際發送它,請將 json_encode() 替換為 http_build_query()

還要擺脫"Content-Length:" header,如果您手動執行它很容易搞砸(也容易出錯)(實際上,您搞砸了!應該有一個空格:和數字,您沒有添加空格,但通常的錯誤是提供錯誤的長度),但如果您不手動執行,則 curl 將自動為您創建 header,這容易出錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM