I am creating a custom module to clear caches on cloudflare for one url. The original curl command:
curl -X POST "https://api.cloudflare.com/client/v4/zones/123456789/purge_cache" -H "Authorization: Bearer 123456789" -H "Content-Type: application/json" --data '{"files": ["https://example.com", {"url": "https://example.com/my-url"}]}'
Drupal::httpClient
try { $client = Drupal::httpClient(); $url = "https://api.cloudflare.com/client/v4/zones/123456789/purge_cache"; $options = [ 'headers' => [ 'Authorization' => 'Bearer 123456789', ], 'json' => [ 'files' => 'https://example.com', 'url' => 'https://example.com/my-url' ], ]; $response = $client->request('POST', $url, $options); $code = $response->getStatusCode(); if ($code == 200) { return $code; } } catch (RequestException $e) { watchdog_exception('module_name', $e); }
php version:
$data = Json::encode(['files' => 'https://example.com', 'url' => 'https://example.com/my-url' ] ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/zones/123456789/purge_cache'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $headers = array(); $headers[] = 'Authorization: Bearer 123456789'; $headers[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_exec($ch); curl_close($ch);
I got one working by clearing all caches on clouldflare. Original:
curl -X POST "https://api.cloudflare.com/client/v4/zones/123456789/purge_cache" -H "Authorization: Bearer 123456789" -H "Content-Type: application/json" --data '{"purge_everything":true}'
The working Drupal Version:
try { $client = Drupal::httpClient(); $options = [ 'json' => [ 'purge_everything' => TRUE, ], 'headers' => [ 'Authorization' => 'Bearer ' . $authorization, ], ]; $response = $client->request($method, $url, $options); $code = $response->getStatusCode(); if ($code == 200) { return $code; } } catch (RequestException $e) { watchdog_exception('cloudflare_purge', $e); }
The drupal version return 200, but it is not doing anything and the php version I could not get it work. I would appreciate any input.