【问题标题】:Why is the curl code not executed in PHP script? (WAMP Server)为什么 PHP 脚本中没有执行 curl 代码? (WAMP 服务器)
【发布时间】:2019-10-08 14:26:58
【问题描述】:

我正在尝试通过 Curl 获取令牌以使用 Microsoft Graph API (https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0)。我已经用这个函数设置了一个简单的 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。这是为什么呢?

【问题讨论】:

  • 使用error_reporting(E_ALL); ini_set('display_errors', '1'); 还有var_dump(extension_loaded('curl')); 显示什么?
  • 它返回 C:\wamp64\www\losapi\losapi.php:8:boolean true
  • 您是否尝试过使用postman 之类的方法来查看是否可以在其他工具中构造请求并查看是否得到预期的响应?
  • @naththedeveloper 是的,在邮递员中它可以工作:)
  • 这对https有帮助吗?

标签: php curl post request wamp


【解决方案1】:

您确定 CURL 已启用,因为您发布的代码没有问题,并且在 curl 执行前后给出回显响应。

【讨论】:

  • 我是这么认为的,因为 var_dump(extension_loaded('curl')) 正在返回 true
  • 其实代码不对,是application/json-encoding和application/x-www-form-urlencoded-encoding混在一起
【解决方案2】:

您以 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,如果你手动操作很容易搞砸(也容易出错)(事实上,你搞砸了!@之间应该有一个空格987654327@ 和数字,您没有添加空格,但通常的错误是提供了错误的长度),但是如果您不手动执行,则 curl 会自动为您创建标题,即 不容易出错。

【讨论】:

  • 感谢您的回复,在文档 (docs.microsoft.com/en-us/graph/…) 中说您应该输入 application/x-www-form-urlencoded :)。顺便说一句,我应用了你的建议,但我仍然没有在“echo $token”取回令牌:(
  • @user3660293 告诉我你applied my suggestions的代码
  • 我没有删除 Content-Length 标头,而是添加了空格。因为它需要一个数组
猜你喜欢
  • 2012-05-22
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 2014-05-25
  • 1970-01-01
相关资源
最近更新 更多