繁体   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