106

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?

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
Bolli
  • 4,714
  • 5
  • 29
  • 45
  • 3
    The internal server error means there was a problem with the script receiving your request. – Brad Nov 16 '12 at 16:55
  • Thanks Brad - I know, I guess its because its not send as DELETE request. If I use a REST client plugin for Firefox and send the exact same request with DELETE, it works fine. So it seams like cURL is not sending the request as DELETE. – Bolli Nov 16 '12 at 17:00
  • Relevant? http://stackoverflow.com/questions/2081894/handling-put-delete-arguments-in-php – Marc B Nov 16 '12 at 17:20
  • Thanks Marc, but it seams like he is doing the same thing as me? Is it impossible to send DELETE requests with PHP? If there is another way withouth cURL, I'm open to use that as well. – Bolli Nov 17 '12 at 12:01

5 Answers5

234

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;
}
Alexis Wilke
  • 15,168
  • 8
  • 60
  • 116
Bolli
  • 4,714
  • 5
  • 29
  • 45
  • can you tell me how we do ajax call to the php(method:delete) that hold this delete curl code and pass it value from ajax ? – user1788736 Sep 18 '13 at 09:09
  • @user1788736 I'm not good at Ajax, but I guess you could create a PHP file that executes this method, and with Ajax send your data using POST to that PHP file. If you think the method above is confusing, look again. $url s simply the server you need to talk with (http://someserver.com) and $path is the stuff after the URL (/something/). The only reason I split these up, is because I need to send to the same server all the time, but with dynamic paths. Hope that makes sense. – Bolli Sep 18 '13 at 09:23
  • I am using same code, And Paypal return http code:204 it mean delete successfully. but I have receive 400 all time. – er.irfankhan11 Oct 09 '15 at 05:39
  • Update 2 is not working ..... When We send postfields then it is not working......... – Muhammad Fahad Mar 26 '16 at 09:51
  • Can we send data in array form instead of json form? – Muhammad Fahad Mar 26 '16 at 09:52
  • @MuhammadFahad Do you need to send data with your delete request? Try sending your data array to the function urlencodeded. $data = urlencode($yourDataArray); curl_del($path, $data); Does that work? – Bolli Mar 26 '16 at 11:33
  • @Bolli : hi, can you please explain what is and what is the value of `$this->__url` . – Prifulnath Mar 29 '17 at 04:30
  • 1
    @kuttoozz that is a private variable in my class. It's simply the URL you need to make requests to. It could be something like http://api.someurl.com and $path is what goes after that url (/something/) . You can simply change that value to your URL or remove it and include the full URL in the $path variable. Does that make sense? – Bolli Mar 29 '17 at 08:15
  • @MuhammadFahad the cURL request accepts json-formatted data, so if you have your array, simply convert to json using json_encode function `json_encode($yourArray);` – Alberto Dec 05 '17 at 10:38
21

To call GET,POST,DELETE,PUT All kind of request, i have created one common function

function CallAPI($method, $api, $data) {
    $url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    switch ($method) {
        case "GET":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            break;
    }
    $response = curl_exec($curl);
    $data = json_decode($response);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check the HTTP Status code
    switch ($httpCode) {
        case 200:
            $error_status = "200: Success";
            return ($data);
            break;
        case 404:
            $error_status = "404: API Not found";
            break;
        case 500:
            $error_status = "500: servers replied with an error.";
            break;
        case 502:
            $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
            break;
        case 503:
            $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
            break;
        default:
            $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
            break;
    }
    curl_close($curl);
    echo $error_status;
    die;
}

CALL Delete Method

$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);

CALL Post Method

$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);

CALL Get Method

$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);

CALL Put Method

$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);
Juned Ansari
  • 4,161
  • 3
  • 43
  • 70
  • well done. Just a note: the http response code for delete is 204. I think you should consider all 20x codes as good response :) – ryuujin Jul 12 '19 at 07:32
0

My own class request with wsse authentication

class Request {

    protected $_url;
    protected $_username;
    protected $_apiKey;

    public function __construct($url, $username, $apiUserKey) {
        $this->_url = $url;     
        $this->_username = $username;
        $this->_apiKey = $apiUserKey;
    }

    public function getHeader() {
        $nonce = uniqid();
        $created = date('c');
        $digest = base64_encode(sha1(base64_decode($nonce) . $created . $this->_apiKey, true));

        $wsseHeader = "Authorization: WSSE profile=\"UsernameToken\"\n";
        $wsseHeader .= sprintf(
            'X-WSSE: UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', $this->_username, $digest, $nonce, $created
        );

        return $wsseHeader;
    }

    public function curl_req($path, $verb=NULL, $data=array()) {                    

        $wsseHeader[] = "Accept: application/vnd.api+json";
        $wsseHeader[] = $this->getHeader();

        $options = array(
            CURLOPT_URL => $this->_url . $path,
            CURLOPT_HTTPHEADER => $wsseHeader,
            CURLOPT_RETURNTRANSFER => true, 
            CURLOPT_HEADER => false             
        );                  

        if( !empty($data) ) {
            $options += array(
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_SAFE_UPLOAD => true
            );                          
        }

        if( isset($verb) ) {
            $options += array(CURLOPT_CUSTOMREQUEST => $verb);                          
        }

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);                   

        if(false === $result ) {
            echo curl_error($ch);
        }
        curl_close($ch);

        return $result; 
    }
}
wpercy
  • 8,491
  • 4
  • 29
  • 39
0
switch ($method) {
    case "GET":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        break;
    case "POST":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        break;
    case "PUT":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        break;
    case "DELETE":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
        break;
}
Unamata Sanatarai
  • 5,609
  • 3
  • 22
  • 46
-19
    $json empty

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

}
UZSTYLE GROUP
  • 17
  • 2
  • 6
  • Thanks. In this particular REST call, the JSON part needs to be empty, so this is no problem. But thanks anyway – Bolli Nov 16 '12 at 17:01
  • What does `$json empty` mean here? It is not in scope inside this function anyway, so the usage of `$json` won't do anything. – halfer Apr 17 '17 at 11:41
  • I have asked for this answer to be deleted, but a moderator has said no. The poster of this answer has not signed in since 2014 anyway. – halfer Apr 18 '17 at 14:11