Make W3 Total Cache “Empty All Caches” function purge varnish [closed]

A simple solution could be to check when you click the “empty all cache” Button with $_GET Like this:

function wpse_16722_purge_varnish() {
    // Is the button submitted, Get the value
    $purge = isset( $_GET['w3tc_note'] ) ? trim( $_GET['w3tc_note'] ) : '';

    // Security-check, user can edit settings
    // And the button "Empty all cache" is submitted
    if( current_user_can('manage_options') && $purge == 'flush_all' ) {

        // Maybe there is a better way to clear the cache 
        // in varnish, i found this on php.net
        // Change this to match your Varnish-setup

        $fp = fsockopen( "127.0.0.1", "80", $errno, $errstr, 2 );

        if ( ! $fp ) {
            echo = "$errstr ($errno)<br />\n";
        } else {
            $out = "PURGE /alain HTTP/1.0\r\n";
            $out .= "Host: giantdorks.org\r\n";
            $out .= "Connection: Close\r\n\r\n";

            fwrite( $fp, $out );

            while ( ! feof( $fp ) ) {
                echo fgets( $fp, 128 );
            }
            fclose( $fp );
        }    
    }
}
add_action('admin_head', 'wpse_16722_purge_varnish');

The Varnish Configuration Language (VCL) also has the url purging function. It’s accessible via the purge_url(url_pattern) function.

acl purge_acl {
    "localhost";
    "some.hostname.ext";
    "154.120.2.33";
}
sub vcl_recv {
    if(req.request == "flush_all") {
        if(!client.ip ~ purge_acl) {
            error 405 "Not allowed";
        } else {
            purge_url(req.url);
            error 200 "Purged";
        }
    }
}

The script above has the normal proxy/cache behaviour for request methods like GET & POST. But when a user connects via the “flush_all” method, the page is purged.

Leave a Comment

tech