将 curl 请求转换为 php-curl - 收到不同的响应

convert a curl request to php-curl - different responses received

我有此请求要使用 owncloud 中的用户配置 API 更新用户。

curl -X PUT https://example.com/ocs/v1.php/cloud/users/pinuccio -d 'key=email' -d 'value=jack@google.com' -H "OCS-APIRequest: true" -u 'admin:adminpwd'

我正在尝试将其转换为 PHP CURL。

到目前为止,我的结果是这样的:

$username = 'admin';
$password = 'adminpwd';
$postData = array(
    'key' => 'email',
    'value' => 'jack@google.com'
);

$ch = curl_init('https://thesmartred.com/cloud/ocs/v1.php/cloud/users/'.$userid);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HEADER, "OCS-APIRequest: true");

curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

$output = curl_exec($ch);
curl_close($ch);
echo $output;

但我收到了 997 的回复。如果我 运行 在 shell 上执行此操作,我会得到 405。为什么我会得到两个不同的答案? 有人可以帮忙吗?

您的命令行请求与 php curl 请求之间存在一些差异。

首先,您使用 CURLOPT_HEADER 的方式有误。在 php curl manual 它说

CURLOPT_HEADER TRUE to include the header in the output

所以要以正确的方式添加header,例如:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'OCS-APIRequest: true'
));

其次,您将数组传递给 post 字段。对于数组,它执行 multipart/form-data post。您需要将数据作为字符串传递,而 http_build_query() 在这种情况下会派上用场。

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));