Search code examples
wordpressdryakismet

Why does Akismet return failed on key verification?


On a self hosted, new installation with version 4.8.1, site with the 2017 default theme I've activated the Akismet plugin with the API key. Modified single.php with:

if (function_exists('akismet_verify_key')) :
    $testing = akismet_verify_key(akismet_get_key(), site_url());
    echo $testing;
endif;

but it always comes back failed. I've made sure the site domain name is included in the Akismet dashboard but for whatever reason after reading the [key verification documentation][1] and detecting the function existed it will not return true.

If I copy the PHP example and change the naming convention of the function to akismet_check:

function akismet_check($key, $blog) {
    $blog           = urlencode($blog);
    $request        = 'key='. $key .'&blog='. $blog;
    $host           = $http_host = 'rest.akismet.com';
    $path           = '/1.1/verify-key';
    $port           = 443;
    $akismet_ua     = "WordPress/4.4.1 | Akismet/3.1.7";
    $content_length = strlen( $request );
    $http_request   = "POST $path HTTP/1.0\r\n";
    $http_request   .= "Host: $host\r\n";
    $http_request   .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $http_request   .= "Content-Length: {$content_length}\r\n";
    $http_request   .= "User-Agent: {$akismet_ua}\r\n";
    $http_request   .= "\r\n";
    $http_request   .= $request;
    $response       = '';
    if (false != ( $fs = @fsockopen( 'ssl://' . $http_host, $port, $errno, $errstr, 10))) :
        fwrite( $fs, $http_request );
        while ( !feof( $fs ) )
            $response .= fgets( $fs, 1160 ); // One TCP-IP packet
            fclose( $fs );
            $response = explode( "\r\n\r\n", $response, 2 );
    endif;
    if ( 'valid' == $response[1] ) :
        return true;
    else :
        return false;
    endif;
}

and pass it:

echo 'Akismet shows ' . $result = akismet_check(akismet_get_key(), site_url());

I do not understand if the function is already present and I can detect it why I'm getting a failure. Does Akismet have an alternative to key verification so I dont have to re-write an entire function to do what seems to already exist if akismet_verify_key doesn't work or am I doing something wrong?


Solution

  • The second parameter to akismet_verify_key() isn't your site URL, it's the IP of the Akismet API server you want to connect to. It's used in Akismet_Admin::check_server_ip_connectivity() to help sites troubleshoot when they can't always connect to the API.

    Changing your call to just $testing = akismet_verify_key( akismet_get_key() ); should work.

    Side note: why are you verifying the Akismet API key inside the theme? Or was that just a simplified example to showcase the problem?