Here's an advanced anti-bot/cloaking system in PHP that uses multiple detection layers and an API key system:

```php
<?php
/**
 * Advanced Anti-Bot & Cloaking System v3.0
 * Place this at the VERY TOP of your index.php (before any output)
 */

// ============================================
// CONFIGURATION
// ============================================
define('ANTIBOT_API_KEY', 'YOUR_API_KEY_HERE'); // Set your API key
define('ANTIBOT_LOG_FILE', __DIR__ . '/antibot_log.txt');
define('ANTIBOT_BLOCK_FILE', __DIR__ . '/antibot_blocks.txt');

// ============================================
// CORE ENGINE
// ============================================
class AdvancedAntiBot {
    private $apiKey;
    private $isBot = false;
    private $botScore = 0;
    private $blockDuration = 3600; // 1 hour block
    private $maxScore = 10;
    private $detectionLayers = [];
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
        $this->detectionLayers = [
            'user_agent' => 3,
            'ip_behavior' => 4,
            'request_headers' => 3,
            'javascript' => 5,
            'rate_limiting' => 4,
            'cloudflare' => 3,
            'referrer' => 2,
            'accept_language' => 2,
            'session_consistency' => 4
        ];
    }
    
    public function run() {
        // Start session for tracking
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        // Check if already blocked
        if ($this->isIPBlocked()) {
            $this->blockRequest('IP is blacklisted');
            return;
        }
        
        // Validate API Key
        if (!$this->validateAPIKey()) {
            die('Invalid API Key. Access Denied.');
        }
        
        // Run all detection layers
        $this->runDetections();
        
        // Calculate final bot score
        $this->calculateBotScore();
        
        // Take action based on score
        $this->takeAction();
    }
    
    private function validateAPIKey() {
        return $this->apiKey === ANTIBOT_API_KEY;
    }
    
    private function runDetections() {
        // Layer 1: User Agent Analysis
        $this->detectByUserAgent();
        
        // Layer 2: IP Reputation & Behavior
        $this->detectByIPBehavior();
        
        // Layer 3: Request Headers Analysis
        $this->detectByHeaders();
        
        // Layer 4: JavaScript Detection (via cookie)
        $this->detectJavaScript();
        
        // Layer 5: Rate Limiting
        $this->detectRateLimiting();
        
        // Layer 6: Cloudflare Detection
        $this->detectCloudflare();
        
        // Layer 7: Referrer Analysis
        $this->detectReferrer();
        
        // Layer 8: Accept Language
        $this->detectAcceptLanguage();
        
        // Layer 9: Session Consistency
        $this->detectSessionConsistency();
    }
    
    // ============================================
    // DETECTION LAYERS
    // ============================================
    
    private function detectByUserAgent() {
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        // Known bot patterns
        $botPatterns = [
            '/bot/i', '/crawl/i', '/spider/i', '/scraper/i',
            '/slurp/i', '/wget/i', '/curl/i', '/python/i',
            '/java/i', '/perl/i', '/ruby/i', '/php/i',
            '/nutch/i', '/yandex/i', '/ahrefs/i', '/semrush/i',
            '/majestic/i', '/rogerbot/i', '/dotbot/i',
            '/googlebot/i', '/bingbot/i', '/baiduspider/i',
            '/duckduckbot/i', '/facebookexternalhit/i',
            '/twitterbot/i', '/linkedinbot/i', '/slackbot/i',
            '/discordbot/i', '/telegrambot/i', '/whatsapp/i',
            '/headless/i', '/phantomjs/i', '/puppeteer/i',
            '/selenium/i', '/playwright/i'
        ];
        
        foreach ($botPatterns as $pattern) {
            if (preg_match($pattern, $ua)) {
                $this->botScore += $this->detectionLayers['user_agent'];
                $this->logDetection('User Agent: ' . $ua);
                break;
            }
        }
        
        // Empty user agent is suspicious
        if (empty($ua)) {
            $this->botScore += 2;
            $this->logDetection('Empty User Agent');
        }
    }
    
    private function detectByIPBehavior() {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        
        // Check if IP is in blocklist
        if ($this->isIPInBlocklist($ip)) {
            $this->botScore += $this->detectionLayers['ip_behavior'];
            $this->logDetection('IP in blocklist: ' . $ip);
        }
        
        // Check request frequency
        $requestCount = $this->getRequestCount($ip);
        if ($requestCount > 50) { // More than 50 requests in short time
            $this->botScore += 3;
            $this->logDetection('High request frequency from IP: ' . $ip);
        }
        
        // Check if IP is from data center
        if ($this->isDataCenterIP($ip)) {
            $this->botScore += 2;
            $this->logDetection('Data center IP detected: ' . $ip);
        }
    }
    
    private function detectByHeaders() {
        $headers = apache_request_headers() ?? [];
        
        // Check for missing common headers
        $commonHeaders = ['Accept', 'Accept-Encoding', 'Accept-Language', 'Connection'];
        $missingHeaders = 0;
        
        foreach ($commonHeaders as $header) {
            if (!isset($headers[$header])) {
                $missingHeaders++;
            }
        }
        
        if ($missingHeaders >= 3) {
            $this->botScore += $this->detectionLayers['request_headers'];
            $this->logDetection('Missing headers count: ' . $missingHeaders);
        }
        
        // Check for suspicious headers
        $suspiciousHeaders = ['X-Forwarded-For', 'X-Originating-IP', 'X-Remote-IP', 'X-Remote-Addr'];
        foreach ($suspiciousHeaders as $sHeader) {
            if (isset($headers[$sHeader])) {
                $this->botScore += 1;
                $this->logDetection('Suspicious header: ' . $sHeader);
            }
        }
    }
    
    private function detectJavaScript() {
        // Check if JS cookie exists (set by our JS script)
        if (isset($_COOKIE['_antibot_js'])) {
            $jsToken = $_COOKIE['_antibot_js'];
            if (!$this->validateJSToken($jsToken)) {
                $this->botScore += $this->detectionLayers['javascript'];
                $this->logDetection('Invalid JS token');
            }
        } else {
            // No JS cookie - could be bot
            $this->botScore += 2;
            $this->logDetection('No JavaScript cookie');
            
            // Inject JS challenge
            $this->injectJSChallenge();
        }
        
        // Check for headless browser
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        if (preg_match('/headless|phantom|puppeteer|selenium/i', $ua)) {
            $this->botScore += $this->detectionLayers['javascript'];
            $this->logDetection('Headless browser detected');
        }
    }
    
    private function detectRateLimiting() {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $key = 'rate_' . $ip;
        
        if (!isset($_SESSION[$key])) {
            $_SESSION[$key] = ['count' => 1, 'time' => time()];
        } else {
            $data = $_SESSION[$key];
            $timeDiff = time() - $data['time'];
            
            if ($timeDiff < 60) { // Within 1 minute
                $data['count']++;
                if ($data['count'] > 30) { // More than 30 requests per minute
                    $this->botScore += $this->detectionLayers['rate_limiting'];
                    $this->logDetection('Rate limit exceeded: ' . $data['count'] . ' requests');
                }
            } else {
                $data['count'] = 1;
                $data['time'] = time();
            }
            $_SESSION[$key] = $data;
        }
    }
    
    private function detectCloudflare() {
        // If using Cloudflare, check CF headers
        if (isset($_SERVER['HTTP_CF_IPCOUNTRY']) || isset($_SERVER['HTTP_CF_RAY'])) {
            // Check if request came through Cloudflare
            if (!isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
                $this->botScore += $this->detectionLayers['cloudflare'];
                $this->logDetection('Missing Cloudflare headers');
            }
            
            // Check threat score if available
            if (isset($_SERVER['HTTP_CF_THREAT_SCORE'])) {
                $score = (int)$_SERVER['HTTP_CF_THREAT_SCORE'];
                if ($score > 30) {
                    $this->botScore += 5;
                    $this->logDetection('Cloudflare threat score: ' . $score);
                }
            }
        }
    }
    
    private function detectReferrer() {
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        
        // Empty referrer for direct access is suspicious
        if (empty($referer)) {
            $this->botScore += 1;
            $this->logDetection('Empty referrer');
        }
        
        // Check if referrer is from known bots
        $botReferrers = ['semrush', 'ahrefs', 'majestic', 'moz', 'seo', 'crawl'];
        foreach ($botReferrers as $botRef) {
            if (stripos($referer, $botRef) !== false) {
                $this->botScore += $this->detectionLayers['referrer'];
                $this->logDetection('Bot referrer: ' . $referer);
                break;
            }
        }
    }
    
    private function detectAcceptLanguage() {
        $acceptLang = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
        
        // Missing accept language is suspicious
        if (empty($acceptLang)) {
            $this->botScore += $this->detectionLayers['accept_language'];
            $this->logDetection('Missing Accept-Language');
        }
        
        // Check for generic accept language that bots use
        if ($acceptLang === 'en-US,en;q=0.9' || $acceptLang === 'en,en-US;q=0.9') {
            $this->botScore += 1;
            $this->logDetection('Generic Accept-Language');
        }
    }
    
    private function detectSessionConsistency() {
        if (!isset($_SESSION['_antibot_session_id'])) {
            $_SESSION['_antibot_session_id'] = bin2hex(random_bytes(16));
        }
        
        // Check if session ID was provided in request (for API calls)
        if (isset($_GET['_session_id']) && $_GET['_session_id'] !== $_SESSION['_antibot_session_id']) {
            $this->botScore += $this->detectionLayers['session_consistency'];
            $this->logDetection('Session mismatch');
        }
        
        // Check for session fixation
        if (isset($_SESSION['_antibot_created']) && $_SESSION['_antibot_created'] < time() - 86400) {
            // Session older than 24h, might be bot
            $this->botScore += 1;
            $this->logDetection('Old session detected');
        }
        
        if (!isset($_SESSION['_antibot_created'])) {
            $_SESSION['_antibot_created'] = time();
        }
    }
    
    // ============================================
    // HELPER FUNCTIONS
    // ============================================
    
    private function calculateBotScore() {
        // Normalize score
        $this->botScore = min($this->botScore, $this->maxScore);
    }
    
    private function takeAction() {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        
        if ($this->botScore >= 7) {
            // High confidence bot - block
            $this->blockIP($ip);
            $this->blockRequest('Bot score: ' . $this->botScore);
        } elseif ($this->botScore >= 5) {
            // Medium confidence - challenge with captcha or redirect
            $this->challengeRequest();
        } elseif ($this->botScore >= 3) {
            // Low confidence - log but allow
            $this->logDetection('Low confidence bot score: ' . $this->botScore);
        }
        
        // Log all detections
        $this->logActivity();
    }
    
    private function blockRequest($reason) {
        header('HTTP/1.1 403 Forbidden');
        die('<h1>Access Denied</h1><p>Your request has been blocked due to suspicious activity.</p>');
    }
    
    private function challengeRequest() {
        // If already challenged, check if passed
        if (isset($_SESSION['_antibot_challenged'])) {
            if ($_SESSION['_antibot_challenged'] === true) {
                return; // Already passed challenge
            }
        }
        
        // Simple math challenge
        $num1 = rand(1, 10);
        $num2 = rand(1, 10);
        $result = $num1 + $num2;
        
        $_SESSION['_antibot_challenge_answer'] = $result;
        $_SESSION['_antibot_challenged'] = false;
        
        // Display challenge
        echo '<!DOCTYPE html>
        <html>
        <head><title>Security Check</title></head>
        <body style="font-family: Arial; max-width: 500px; margin: 100px auto; text-align: center;">
            <h2>Security Verification</h2>
            <p>Please solve this simple math problem to continue:</p>
            <form method="POST">
                <div style="font-size: 24px; margin: 20px 0;">
                    ' . $num1 . ' + ' . $num2 . ' = <input type="number" name="challenge_answer" required>
                </div>
                <input type="submit" value="Verify" style="padding: 10px 30px; font-size: 16px;">
                <input type="hidden" name="_antibot_challenge" value="1">
            </form>
        </body>
        </html>';
        exit;
    }
    
    private function isIPBlocked() {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        
        if (!file_exists(ANTIBOT_BLOCK_FILE)) {
            return false;
        }
        
        $blocks = file(ANTIBOT_BLOCK_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $now = time();
        
        foreach ($blocks as $block) {
            list($blockedIP, $timestamp) = explode('|', $block);
            if ($blockedIP === $ip && ($now - $timestamp) < $this->blockDuration) {
                return true;
            }
        }
        
        return false;
    }
    
    private function blockIP($ip) {
        $entry = $ip . '|' . time() . "\n";
        file_put_contents(ANTIBOT_BLOCK_FILE, $entry, FILE_APPEND | LOCK_EX);
    }
    
    private function isIPInBlocklist($ip) {
        // Check against public blocklists (example with abuseipdb)
        // You would implement API calls here
        
        // For now, check local blocklist
        if (!file_exists(ANTIBOT_BLOCK_FILE)) {
            return false;
        }
        
        $blocks = file(ANTIBOT_BLOCK_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($blocks as $block) {
            list($blockedIP, $timestamp) = explode('|', $block);
            if ($blockedIP === $ip) {
                return true;
            }
        }
        
        return false;
    }
    
    private function getRequestCount($ip) {
        $key = 'requests_' . $ip;
        if (!isset($_SESSION[$key])) {
            $_SESSION[$key] = 1;
            return 1;
        }
        return $_SESSION[$key]++;
    }
    
    private function isDataCenterIP($ip) {
        // Check if IP belongs to known data centers
        // You can implement IP range checks or use an API
        
        $dataCenterRanges = [
            '52.0.0.0/8',  // AWS
            '54.0.0.0/8',  // AWS
            '35.0.0.0/8',  // GCP
            '34.0.0.0/8',  // GCP
            '13.0.0.0/8',  // AWS
            '18.0.0.0/8',  // AWS
            '104.0.0.0/8', // Google
            '108.0.0.0/8', // Google
            '167.0.0.0/8', // DigitalOcean
            '159.0.0.0/8', // DigitalOcean
        ];
        
        $ipLong = ip2long($ip);
        foreach ($dataCenterRanges as $range) {
            list($network, $mask) = explode('/', $range);
            $networkLong = ip2long($network);
            $maskLong = ~((1 << (32 - $mask)) - 1);
            if (($ipLong & $maskLong) == ($networkLong & $maskLong)) {
                return true;
            }
        }
        
        return false;
    }
    
    private function validateJSToken($token) {
        // Validate the JS token
        return isset($_SESSION['_antibot_js_secret']) && 
               hash_equals($_SESSION['_antibot_js_secret'], $token);
    }
    
    private function injectJSChallenge() {
        $secret = bin2hex(random_bytes(32));
        $_SESSION['_antibot_js_secret'] = $secret;
        
        // The actual JS challenge would be injected here
        // This is a simplified version
        echo '<script>
            document.cookie = "_antibot_js=' . $secret . '; path=/";
            // Also check if cookies are enabled
            if (!navigator.cookieEnabled) {
                // Redirect to a "cookies required" page
                window.location.href = "?error=cookies_required";
            }
        </script>';
    }
    
    private function logDetection($message) {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $this->detectionLayers['log'][] = [
            'time' => date('Y-m-d H:i:s'),
            'ip' => $ip,
            'message' => $message
        ];
    }
    
    private function logActivity() {
        if (!file_exists(ANTIBOT_LOG_FILE)) {
            file_put_contents(ANTIBOT_LOG_FILE, "=== AntiBot Log Started ===\n");
        }
        
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $logEntry = date('Y-m-d H:i:s') . ' | IP: ' . $ip . ' | Score: ' . $this->botScore . "\n";
        
        if (!empty($this->detectionLayers['log'])) {
            foreach ($this->detectionLayers['log'] as $log) {
                $logEntry .= '  - ' . $log['message'] . "\n";
            }
        }
        
        $logEntry .= str_repeat('-', 80) . "\n";
        file_put_contents(ANTIBOT_LOG_FILE, $logEntry, FILE_APPEND | LOCK_EX);
    }
}

// ============================================
// INITIALIZATION
// ============================================

// Check for challenge response
if (isset($_POST['_antibot_challenge']) && isset($_POST['challenge_answer'])) {
    session_start();
    if (isset($_SESSION['_antibot_challenge_answer']) && 
        (int)$_POST['challenge_answer'] === (int)$_SESSION['_antibot_challenge_answer']) {
        $_SESSION['_antibot_challenged'] = true;
        unset($_SESSION['_antibot_challenge_answer']);
        // Redirect to clear POST data
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    } else {
        die('Incorrect answer. Please try again.');
    }
}

// Run the anti-bot system
$antibot = new AdvancedAntiBot('YOUR_API_KEY_HERE');
$antibot->run();

// ============================================
// END OF ANTIBOT SYSTEM
// ============================================
?>
```

Installation & Usage

1. Set your API Key:
   ```php
   define('ANTIBOT_API_KEY', 'your-secure-api-key-here');
   ```
2. Place the code at the top of your index.php:
   ```php
   <?php
   // Copy the entire anti-bot code here
   // Your regular website code follows below
   ?>
   ```
3. Add JavaScript challenge (optional but recommended):
   Create antibot.js and include it:
   ```javascript
   // AntiBot JavaScript Challenge
   (function() {
       // Set cookie to prove JavaScript execution
       document.cookie = "_antibot_js=" + btoa(Date.now()) + "; path=/";
       
       // Check if cookies are enabled
       if (!navigator.cookieEnabled) {
           window.location.href = "?error=cookies_required";
       }
       
       // Add more sophisticated checks
       var canvas = document.createElement('canvas');
       var ctx = canvas.getContext('2d');
       var txt = 'AntiBot';
       ctx.textBaseline = 'top';
       ctx.font = '14px Arial';
       ctx.fillStyle = '#f60';
       ctx.fillRect(125,1,62,20);
       ctx.fillStyle = '#069';
       ctx.fillText(txt, 2, 15);
       ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
       ctx.fillText(txt, 4, 17);
       
       // Send fingerprint to server
       var fingerprint = canvas.toDataURL();
       // You can send this via AJAX to validate
   })();
   ```

Features

· 9 Detection Layers: User Agent, IP Behavior, Headers, JavaScript, Rate Limiting, Cloudflare, Referrer, Accept Language, Session Consistency
· Scoring System: Each layer contributes to a bot score
· Auto-blocking: Blocks high-confidence bots
· Challenge System: Presents math CAPTCHA for medium-suspicion requests
· IP Blacklisting: Temporary blocks for malicious IPs
· Cloudflare Integration: Uses Cloudflare threat scores if available
· Detailed Logging: All detections are logged
· Session-based Tracking: Monitors user session behavior

Advanced Features

1. Data Center IP Detection: Identifies requests from hosting providers
2. Headless Browser Detection: Detects Puppeteer, Selenium, PhantomJS
3. Request Rate Limiting: Prevents rapid-fire requests
4. JavaScript Challenge: Requires actual browser execution
5. Cloudflare Integration: Leverages Cloudflare's threat intelligence

Security Notes

· Always keep your API key secure
· Regularly review the log file for false positives
· Adjust scores based on your traffic patterns
· Consider using a CDN or DDoS protection alongside
· The system uses server-side detection as primary defense

This provides enterprise-level bot protection while maintaining good user experience for legitimate visitors.