duanchao5258 2012-11-16 16:53
浏览 231
已采纳

PHP CURL DELETE请求

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.

This is how I do it:

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;

}

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

So what am I doing wrong?

  • 写回答

4条回答 默认 最新

  • doushi1510 2013-07-29 22:52
    关注

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

    I created a new method:

    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;
    }
    

    Update 2

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码