如何使用 cURL 在 PHP 中发出 PATCH 请求?

我必须使用 PhPcURL 发出 PATCH 请求。我找不到任何文档,所以我尝试了以下方法,但是没有用。

$data = "{'field_name': 'field_value'}";
$url = "http://webservice.url";
$headers = array('X-HTTP-Method-Override: PATCH');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);

知道为什么这个不管用吗? 我怎么才能修好它?

编辑: 我正在连接到一个 RESTful Web 服务。对于成功的请求,它返回 HTTP/1.1200。不成功的请求返回 HTTP/1.1403。我一直收到403。

我试着把 $data 改成:

$data = "data={'field_name': 'field_value'}";

这并没有改变结果。

编辑2: 最终工作代码。

$data = "{'field_name': 'field_value'}";
$url = "http://webservice.url";
$headers = array('Content-Type: application/json');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
67760 次浏览

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH'); should do it.

Try Using normal array

//$data = "{'field_name': 'field_value'}";

$data = array('field_name' => 'field_value' );

JSON PATCH would be better for data format since this format is designed for HTTP PATCH request. See https://www.rfc-editor.org/rfc/rfc6902 for the spec. The tutorial of Rails 4 show the example(http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#http-patch).

// https://www.rfc-editor.org/rfc/rfc6902#section-4
$data = '{ "op": "add", "path": "/a/b/c", "value": "foo" }';
$headers = array('Content-Type: application/json-patch+json');

You can define methods and use everything in one curl function. Hope this helps you.

define('GI_HTTP_METHOD_GET', 'GET');
define('GI_HTTP_METHOD_POST', 'POST');
define('GI_HTTP_METHOD_PUT', 'PUT');
define('GI_HTTP_METHOD_PATCH', 'PATCH');


curl_setopt($ch, CURLOPT_POST, true);
if ($method === GI_HTTP_METHOD_PUT) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, GI_HTTP_METHOD_PUT);
}
if ($method === GI_HTTP_METHOD_PATCH) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, GI_HTTP_METHOD_PATCH);
}