【问题标题】:Why the PHP curl is not working? When it works from command line curl?为什么 PHP curl 不起作用?当它从命令行 curl 工作时?
【发布时间】:2019-05-22 21:02:42
【问题描述】:

当我从命令行执行如下操作时:

$ curl -X "POST" "https://ABCD/login/oauth2/access_token"  -H "Authorization: Basic XXXX="  -H "Content-Type:application/x-www-form-urlencoded"  --data-urlencode "realm=XXX"  --data-urlencode "XXX=XXX"

但是当我从 PHP 中执行它时它不起作用:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://ABCD/login/oauth2/access_token');
curl_setopt($ch, CURLOPT_POST, 1);

$ss = array(
  'realm' => 'XXX',
  'XXX'=>'XXX'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($ss));    

curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 


curl_setopt($ch, CURLOPT_HTTPHEADER, 
array(
  'Authorization: Basic XXXX=',
  'Content-Type: application/x-www-form-urlencoded',     
));

$result=curl_exec ($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);

知道我做错了什么吗?我收到“必需参数或正文丢失或不正确”的 HTTP 状态。

【问题讨论】:

  • 使用 curl_setopt($ch, CURLOPT_VERBOSE, 1); 并将 PHP 输出与 curl -v 输出进行比较,以验证您发送的标头和有效负载是否完全相同。
  • 它仍然无法正常工作。我一路尝试。只有 curl 7.29.0 (x86_64-redhat-linux-gnu) 通过命令行工作。但是 PHP curl 还没有失败。

标签: php curl centos


【解决方案1】:

您的命令行显示 --data-urlencode — URL 编码

你的 PHP 说 'Content-Type: application/x-www-form-urlencoded', — 所以你你是对数据进行 URL 编码

它还写着 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($ss)); — 所以你是 JSON 编码 它而不是 URL 编码它。

发送您声称要发送的 URL 编码数据。

【讨论】:

  • 当我通过删除 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($ss)); 发送 curl_setopt($ch, CURLOPT_URL, 'https://ABCD/login/oauth2/access_token?realm=XXX&XXX=XXX'); 时,它现在报告 HTTP 错误 500 An internal server error occurred.
  • @YumYumYum — 你为什么将数据放在查询字符串而不是请求正文中?
  • curl_setopt($ch, CURLOPT_POSTFIELDS, 'realm=XXX&XXX=XXX'); - 当我现在这样发送它时它仍然失败。
  • 为什么还是不行?它是我的 CentOS 3.10.0-693.21.1.el7.x86_64 上 PHP 5.4.16 的 BUG 吗? (命令行中的 curl 7.29.0 (x86_64-redhat-linux-gnu) 有效)
猜你喜欢
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2014-01-26
相关资源
最近更新 更多