How to write PHP curl DELETE request

18,079

Solution 1

Try This

Change the CUTLOPT_CUSTOMREQUEST to "DELETE" Find More

$ch = curl_init('https://api.digitalocean.com/v2/droplets/18160706');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer MY_API_TOKEN')
);

$result = curl_exec($ch);
echo $result;

Solution 2

You need to set CURLOPT_CUSTOMREQUEST to DELETE as mentioned in the PHP Manual here. Please take some time to read it. The following code should work

$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);
Share:
18,079
user1661677
Author by

user1661677

Updated on June 13, 2022

Comments

  • user1661677
    user1661677 almost 2 years

    I'm referencing DigitalOcean's API docs, and they give the following example on how to delete a droplet here:

    curl -X DELETE -H "Content-Type: application/json" -H "Authorization: Bearer API_TOKEN" "https://api.digitalocean.com/v2/droplets/[DROPLET_ID]"
    

    How can I write this in PHP curl?

    I currently have this:

    $ch = curl_init('https://api.digitalocean.com/v2/droplets/18160706');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer MY_API_TOKEN')
    );
    
    $result = curl_exec($ch);
    echo $result;
    

    But that is not deleting my droplet and is returning (Yes, the droplet id is correct):

    {"id":"not_found","message":"The resource you were accessing could not be found."}1
    
  • Cas
    Cas over 7 years
    I used this to send a delete request, but still the API I'm interacting with (Mollie) doesn't allow it. They respond with a 405 status code and header Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS, DELETE. Any idea?
  • Gohel Kiran
    Gohel Kiran over 7 years
    Same issue for me, with nginx, php-fpm and slim everything works fine from swagger, but from phpunit test case it gives {"status":405,"error":"Method DELETE not in allowed methods (POST, GET)"}