我只是想在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);
但这并未改变服务器的响应。
答案 0 :(得分:1)
我想出了丢失的一块。我需要将CURLOPT_POSTFIELDS
显式设置为null:
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
添加该行之后,现在的工作就像使用shell命令一样。