这个 curl 命令与我的 php 代码有何不同


How does this curl command differ from my php code?

我只是想在PHP中复制这个curl命令:

curl -X POST -H 'Content-Type: application/xml' -u username:password https://api.company.com/api/path

这是我正在使用的PHP代码:

$ch = curl_init("https://api.company.com/api/path");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/xml"));
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);  // $response is null
$info = curl_getinfo($ch);   // $info['http_code'] is 400

当我的 shell 命令成功并且我从服务器获取数据时,此 PHP 代码失败 - 服务器返回 400 错误。据我所知,PHP 代码和 shell 命令实际上是相同的,那么我缺少什么区别?


编辑:

这是我从详细模式获得的信息:

* About to connect() to api.company.com port 443 (#0)
*   Trying xxx.xxx.xxx.xxx...
* connected
* Connected to api.company.com (xxx.xxx.xxx.xxx) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* SSL connection using AES256-SHA
* Server certificate:
*    [...]
*    SSL certificate verify ok.
* Server auth using Basic with user 'username'
> POST /api/path HTTP/1.1
Authorization: Basic [...]
Host: api.company.com
Accept: */*
Content-Type: application/xml
Content-Length: -1
Expect: 100-continue
< HTTP/1.1 400 BAD_REQUEST
< Content-Length: 0
< Connection: Close
< 
* Closing connection #0

编辑 2

我尝试在脚本中添加以下内容:

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

但这并没有改变服务器的响应。

我找出了缺失的部分。我需要将CURLOPT_POSTFIELDS显式设置为 null:

curl_setopt($ch, CURLOPT_POSTFIELDS, null);

添加该行后,现在的工作方式就像使用 shell 命令一样。