尽管返回了状态码200,为什么PHP cURL PUT请求仍然无法工作?

时间:2019-03-15 14:01:10

标签: php curl request put

我已经被这个问题困扰了一段时间了。我正在尝试使用REST API更改用户的某些设置,例如清除用户并将其设备设置为非活动状态。

REST调用是用php进行的,这是我的新手。大多数调用(获取和发布)都工作正常,所以我想我了解php和curl的基本概念,但我无法使put请求工作。问题是,在进行REST调用时,我得到的状态码为200,表示一切正常,但是当我检查数据库时,没有任何更改,并且设备仍处于活动状态。

我已经花了几个小时在stackexchange(cURL PUT Request Not Working with PHPPhp Curl return 200 but not postingPHP CURL PUT function not working)上研究此问题,并另外阅读了各种教程。 对我来说,我的代码看起来不错,并且非常合理,类似于我在网上找到的许多示例。因此,请帮助我找到我的错误。

$sn = "123456789";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/sn/".$sn);

$data = array("cmd" => "clearUser");
$headers = array(
    'Accept: application/json',
    'Content-Type: application/json'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$username = 'XXX';
$password = 'XXX';
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

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

3 个答案:

答案 0 :(得分:0)

您在标题“ Content-Type:应用程序/ json”中定义。尝试将$ data编码为json,然后传输jsonEncodeteData:

$dataJson = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);

也许这已经有所帮助。

答案 1 :(得分:0)

在PUT请求的情况下,状态200可能不会成功。用正确的语义(服务器的正确实现),成功的PUT将返回“ 201 Created”,并且,如果客户端发送的内容为空或错误的内容,则服务器将返回“ 204 No Content”。

懒惰的程序员可能只是返回“ 200 Ok”而不是204,意思是“您的请求很好,但是与数据无关”。

尝试验证您的数据,并确保发送的内容不为空且符合API规范。

答案 2 :(得分:0)

据我所知,您的代码中有两个问题。

  1. Content-Type: application/json不正确,我将其完全删除。
  2. 您没有Content-Length标头。

我建议尝试

$sn = "123456789";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/sn/".$sn);

$data = array("cmd" => "clearUser");
$httpQuery = http_build_query($data);
$headers = array(
    'Accept: application/json',
    'Content-Length: ' . strlen($httpQuery)
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$username = 'XXX';
$password = 'XXX';
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$httpQuery);

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