2

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
user1661677
  • 1,062
  • 5
  • 12
  • 28

2 Answers2

5

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);
Michael D
  • 20,838
  • 4
  • 12
  • 37
5

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;
Naresh Kumar
  • 543
  • 2
  • 15
  • 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? – Cas Eliëns Nov 22 '16 at 15:36
  • 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)"} – Gohel Kiran Jan 05 '17 at 04:04