PHP CURL DELETE 请求 [英] PHP CURL DELETE request

查看:49
本文介绍了PHP CURL DELETE 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PHP 和 cURL 执行 DELETE http 请求.

I'm trying to do a DELETE http request using PHP and cURL.

我已经阅读了很多地方的操作方法,但似乎对我没有任何作用.

I have read how to do it many places, but nothing seems to work for me.

我是这样做的:

public function curl_req($path,$json,$req)
{
    $ch = curl_init($this->__url.$path);
    $data = json_encode($json);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data)));
    $result = curl_exec($ch);
    $result = json_decode($result);
    return $result;
}

然后我继续使用我的函数:

I then go ahead and use my function:

public function deleteUser($extid)
{
    $path = "/rest/user/".$extid."/;token=".$this->__token;
    $result = $this->curl_req($path,"","DELETE");
    return $result;

}

这给了我 HTTP 内部服务器错误.在我使用相同 curl_req 方法和 GET 和 POST 的其他函数中,一切顺利.

This gives me HTTP internal server ERROR. In my other functions using the same curl_req method with GET and POST, everything goes well.

那我做错了什么?

推荐答案

我终于自己解决了.如果其他人遇到此问题,这是我的解决方案:

I finally solved this myself. If anyone else is having this problem, here is my solution:

我创建了一个新方法:

public function curl_del($path)
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $result;
}

更新 2

由于这似乎对某些人有帮助,这里是我最后的 curl DELETE 方法,它返回 JSON 解码对象中的 HTTP 响应:

Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:

  /**
 * @desc    Do a DELETE request with cURL
 *
 * @param   string $path   path that goes after the URL fx. "/user/login"
 * @param   array  $json   If you need to send some json with your request.
 *                         For me delete requests are always blank
 * @return  Obj    $result HTTP response from REST interface in JSON decoded.
 */
public function curl_del($path, $json = '')
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $result = json_decode($result);
    curl_close($ch);

    return $result;
}

这篇关于PHP CURL DELETE 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆