Skip to content

Magento 2 how to purge varnish cache programatically when flush magento cache

private function purgeVarnishCache($url)
    {
        try {
            // Trigger Varnish cache purge by sending a PURGE request
            $this->curlClient->setHeaders(['Host' => parse_url($url, PHP_URL_HOST)]);
            $this->curlClient->addHeader('Host', parse_url($url, PHP_URL_HOST));
            $getTest = $this->curlClient->setOption(CURLOPT_CUSTOMREQUEST, 'PURGE');
            $this->curlClient->setOption(CURLOPT_URL, $url);
            $this->curlClient->setOption(CURLOPT_RETURNTRANSFER, true);

            // Execute the request and get the response body
            $responseBody = $this->curlClient->getBody();
            // Log or output a message (optional)
            echo "Varnish cache purged for URL: $urln";exit();
        } catch (Exception $e) {
            // Handle exceptions (optional)
            echo "Error purging Varnish cache: " . $e->getMessage() . "n";exit();
        }
    }