PHP code example of florentingarnier / spam-protection

1. Go to this page and download the library: Download florentingarnier/spam-protection 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/ */

    

florentingarnier / spam-protection example snippets


use FlorentinGarnier\SpamProtection\IpReputation\IpReputation;
use FlorentinGarnier\SpamProtection\IpReputation\IpReputationList;
use FlorentinGarnier\SpamProtection\SpamProtection;

$spamProtection = SpamProtection::create(
    secret: $appSecret,         // long random string, signs the tokens
    cache: $cachePool,          // any PSR-6 pool
    ipReputation: new IpReputation(new IpReputationList(__DIR__.'/var/ip_reputation.php')),
    baseDifficulty: 10,         // optional
    maximumAttemptsPerHour: 20, // optional
    tokenLock: $tokenLock,      // recommended, see below
);

$challenge = $spamProtection->issueChallenge('contact', $clientIp);

use FlorentinGarnier\SpamProtection\Submission;

$verdict = $spamProtection->verify(new Submission(
    scope: 'contact',
    honeypot: $_POST['fax_number'] ?? '',
    submissionToken: $_POST['rendered_at'] ?? '',
    proofOfWorkChallenge: $_POST['proof_challenge'] ?? '',
    proofOfWorkSolution: $_POST['proof_solution'] ?? '',
    contents: [$_POST['message'] ?? ''],
), $clientIp);

if (!$verdict->isAccepted()) {
    $logger->warning('Spam rejected', [
        'reason' => $verdict->rejectionReason->value,
        'ip_risk' => $verdict->ipRiskLevel->value,
    ]);
    // Display the form again, with a fresh challenge.
}

use FlorentinGarnier\SpamProtection\IpReputation\IpRangeSet;

(new IpReputationList(__DIR__.'/var/ip_reputation.php'))->save([
    'hosting' => IpRangeSet::fromCidrs(explode("\n", file_get_contents('https://raw.githubusercontent.com/X4BNet/lists_vpn/main/output/datacenter/ipv4.txt'))),
    'tor' => IpRangeSet::fromCidrs(explode("\n", file_get_contents('https://check.torproject.org/torbulkexitlist'))),
]);

$token = SpamProtectionTestHelper::forgeSubmissionToken($secret, 'contact', time() - 4);
$solution = SpamProtectionTestHelper::solveProofOfWork($challenge->proofOfWorkChallenge, $challenge->difficulty);