PHP code example of automattic / akismet-sdk

1. Go to this page and download the library: Download automattic/akismet-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

automattic / akismet-sdk example snippets




use Automattic\Akismet\Akismet;
use Automattic\Akismet\DTO\Content;
use Automattic\Akismet\Enum\ContentType;

// Initialize the client
$akismet = Akismet::create(
    apiKey: 'your-api-key',
    site: 'https://your-site.com'
);

// Check if content is spam
$content = new Content(
    userIp: $_SERVER['REMOTE_ADDR'],
    userAgent: $_SERVER['HTTP_USER_AGENT'],
    body: $formData['message'],
    authorName: $formData['name'],
    authorEmail: $formData['email'],
    type: ContentType::ContactForm
);

$result = $akismet->check($content);

if ($result->isSpam()) {
    // Handle spam
    if ($result->shouldDiscard()) {
        // Blatant spam - safe to discard silently
    }
} else {
    // Process legitimate submission
}

$akismet = Akismet::create(
    apiKey: 'your-api-key',
    site: 'https://your-site.com',
    applicationUserAgent: 'MyDrupalModule/1.0.0'
);

use Automattic\Akismet\Factory\ContentFactory;
use Automattic\Akismet\Enum\ContentType;

$content = ContentFactory::fromRequest(
    request: $psr7Request,
    body: $formData['message'],
    authorName: $formData['name'],
    authorEmail: $formData['email'],
    type: ContentType::ContactForm,
);

// Trust specific proxy IPs
$content = ContentFactory::fromRequest(
    request: $psr7Request,
    body: $formData['message'],
    trustedProxies: ['10.0.0.1', '10.0.0.2'],
);

// Trust all proxies (use only in controlled environments)
$content = ContentFactory::fromRequest(
    request: $psr7Request,
    body: $formData['message'],
    trustedProxies: ['*'],
);

// Report a missed spam (was marked as ham but is actually spam)
$akismet->submitSpam($content);

// Report a false positive (was marked as spam but is actually ham)
$akismet->submitHam($content);

use Automattic\Akismet\Exception\AkismetException;
use Automattic\Akismet\Exception\InvalidApiKeyException;
use Automattic\Akismet\Exception\RateLimitException;

try {
    $result = $akismet->check($content);
} catch (InvalidApiKeyException $e) {
    // API key is invalid or revoked
} catch (RateLimitException $e) {
    // Too many requests — retry after $e->getRetryAfter() seconds
} catch (AkismetException $e) {
    // Catch-all for network errors, server errors, validation errors, etc.
}

$akismet = Akismet::create(
    apiKey: 'your-api-key',
    site: 'https://your-site.com',
    isTest: true
);