### Install TrustCaptcha PHP Dependency Source: https://github.com/trustcomponent/trustcaptcha-php/blob/master/README.md Use Composer to install the TrustCaptcha PHP library. This is the first step to integrating TrustCaptcha into your PHP project. ```bash composer require trustcomponent/trustcaptcha-php ``` -------------------------------- ### Verify CAPTCHA Result via Proxy Source: https://context7.com/trustcomponent/trustcaptcha-php/llms.txt Configure proxy settings when your server needs a proxy to access external APIs. This example demonstrates passing proxy options, including authentication credentials. ```php 'http://proxy.example.com:8080', 'username' => 'proxy_user', 'password' => 'proxy_password' ]; // Also supports tcp:// protocol prefix (automatically converted to http://) $proxyOptionsTcp = [ 'proxy' => 'tcp://proxy.example.com:8080' ]; try { $result = CaptchaManager::getVerificationResult($secretKey, $verificationToken, $proxyOptions); if ($result->verificationPassed) { echo "Verification passed via proxy!"; } } catch (Exception $e) { error_log("Proxy connection failed: " . $e->getMessage()); } ``` -------------------------------- ### Integrate TrustCaptcha into a Contact Form Source: https://context7.com/trustcomponent/trustcaptcha-php/llms.txt Implements a form handler that validates user input and verifies the TrustCaptcha token. Requires the TrustCaptcha SDK and proper handling of specific verification exceptions. ```php false, 'error' => 'Missing required fields']; } // Validate CAPTCHA token is present if (empty($_POST['trustcaptcha_verification_token'])) { return ['success' => false, 'error' => 'CAPTCHA verification required']; } // Verify the CAPTCHA $captchaResult = $this->verifyCaptcha($_POST['trustcaptcha_verification_token']); if (!$captchaResult['passed']) { return ['success' => false, 'error' => $captchaResult['error']]; } // CAPTCHA passed - process the form $this->processContactForm( $_POST['email'], $_POST['message'], $captchaResult['metadata'] ); return ['success' => true, 'message' => 'Form submitted successfully']; } private function verifyCaptcha(string $token): array { try { $result = CaptchaManager::getVerificationResult(self::SECRET_KEY, $token); // Check verification status and bot score if (!$result->verificationPassed) { return [ 'passed' => false, 'error' => 'CAPTCHA verification failed' ]; } if ($result->score > self::MAX_BOT_SCORE) { // Log suspicious activity error_log(sprintf( "High bot score detected: %s from %s (%s/%s)", $result->score, $result->ipAddress, $result->browser, $result->operatingSystem )); return [ 'passed' => false, 'error' => 'Automated request detected' ]; } return [ 'passed' => true, 'metadata' => [ 'verification_id' => $result->verificationId, 'score' => $result->score, 'ip' => $result->ipAddress, 'device' => $result->deviceFamily, 'browser' => $result->browser ] ]; } catch (VerificationTokenInvalidException $e) { return ['passed' => false, 'error' => 'Invalid CAPTCHA token']; } catch (VerificationNotFoundException $e) { return ['passed' => false, 'error' => 'CAPTCHA session expired']; } catch (VerificationNotFinishedException $e) { return ['passed' => false, 'error' => 'Please complete the CAPTCHA']; } catch (SecretKeyInvalidException $e) { error_log('TrustCaptcha: Secret key configuration error'); return ['passed' => false, 'error' => 'Server configuration error']; } catch (Exception $e) { error_log('TrustCaptcha error: ' . $e->getMessage()); return ['passed' => false, 'error' => 'Verification service unavailable']; } } private function processContactForm(string $email, string $message, array $metadata): void { // Store submission with CAPTCHA metadata for audit $submission = [ 'email' => $email, 'message' => $message, 'captcha_verification_id' => $metadata['verification_id'], 'captcha_score' => $metadata['score'], 'client_ip' => $metadata['ip'], 'submitted_at' => date('Y-m-d H:i:s') ]; // Save to database, send notification, etc. // ... } } // Handle the form submission $handler = new ContactFormHandler(); $response = $handler->handleSubmission(); header('Content-Type: application/json'); echo json_encode($response); ``` -------------------------------- ### Accessing VerificationResult Properties in PHP Source: https://context7.com/trustcomponent/trustcaptcha-php/llms.txt Retrieve and access various properties from the VerificationResult object to implement security logic. This includes core verification status, bot detection scores and reasons, client information, and timestamps. Ensure the TrustComponent library is autoloaded. ```php captchaId; // string: Your CAPTCHA configuration ID $verificationId = $result->verificationId; // string: Unique ID for this verification $verificationPassed = $result->verificationPassed; // bool: Overall pass/fail status // Bot detection $score = $result->score; // float: Bot probability (0.0 = human, 1.0 = bot) $reason = $result->reason; // string: Explanation of score factors $mode = $result->mode; // string: Verification mode used // Client information $origin = $result->origin; // string: Origin URL of the request $ipAddress = $result->ipAddress; // string: Client IP address $deviceFamily = $result->deviceFamily; // string: Device type (Desktop, Mobile, etc.) $operatingSystem = $result->operatingSystem; // string: Client OS (Windows, macOS, etc.) $browser = $result->browser; // string: Browser name (Chrome, Firefox, etc.) // Timestamps $creationTimestamp = $result->creationTimestamp; // string: When verification was initiated $releaseTimestamp = $result->releaseTimestamp; // string: When verification was completed $retrievalTimestamp = $result->retrievalTimestamp; // string: When result was retrieved // Example: Implement tiered security based on bot score if (!$result->verificationPassed) { // Block - verification failed completely die("Access denied"); } elseif ($result->score > 0.7) { // High bot probability - block or require additional verification die("Additional verification required"); } elseif ($result->score > 0.3) { // Medium suspicion - allow but log for review error_log("Suspicious request from {$result->ipAddress}, score: {$result->score}"); // Continue processing... } else { // Low score - likely human // Process normally } ``` -------------------------------- ### Retrieve CAPTCHA Verification Result in PHP Source: https://github.com/trustcomponent/trustcaptcha-php/blob/master/README.md Fetch the verification result from TrustCaptcha using your secret key and the verification token provided by the client. Handle potential exceptions during the fetch process. ```php // Retrieving the verification result $verificationResult = null; try { $verificationResult = CaptchaManager::getVerificationResult("", ""); } catch (Exception $e) { // Fetch verification result failed - handle error } ``` -------------------------------- ### Verify CAPTCHA Result with CaptchaManager Source: https://context7.com/trustcomponent/trustcaptcha-php/llms.txt Verify the CAPTCHA token received from the client-side widget. This method checks the verification status and bot score, handling various exceptions for invalid keys, tokens, or verification states. ```php verificationPassed && $result->score <= 0.5) { // Human user - process the form echo "Verification successful!"; echo "Verification ID: " . $result->verificationId; echo "Bot Score: " . $result->score; echo "Device: " . $result->deviceFamily; echo "Browser: " . $result->browser; echo "OS: " . $result->operatingSystem; } else { // Likely a bot - reject the request http_response_code(403); echo "Verification failed - possible bot detected."; } } catch (SecretKeyInvalidException $e) { // Your API secret key is invalid error_log("TrustCaptcha: Invalid secret key"); http_response_code(500); } catch (VerificationTokenInvalidException $e) { // The verification token from the client is malformed error_log("TrustCaptcha: Invalid verification token"); http_response_code(400); } catch (VerificationNotFoundException $e) { // The verification ID does not exist error_log("TrustCaptcha: Verification not found"); http_response_code(400); } catch (VerificationNotFinishedException $e) { // The user hasn't completed the CAPTCHA yet error_log("TrustCaptcha: Verification not finished"); http_response_code(400); } catch (Exception $e) { // Network or other errors error_log("TrustCaptcha error: " . $e->getMessage()); http_response_code(500); } ``` -------------------------------- ### Act on CAPTCHA Verification Result in PHP Source: https://github.com/trustcomponent/trustcaptcha-php/blob/master/README.md Check if the CAPTCHA verification passed and if the bot score is acceptable. This logic determines whether to proceed with the user's request or flag it as potentially automated. ```php // Act on the verification result if (!$verificationResult->verificationPassed || $verificationResult->score > 0.5) { echo "Verification failed or bot score > 0.5 – possible automated request."; } ``` -------------------------------- ### CaptchaManager::getVerificationResult Source: https://context7.com/trustcomponent/trustcaptcha-php/llms.txt Validates a CAPTCHA verification token against the TrustCaptcha API to determine if the user is a human or a bot. ```APIDOC ## CaptchaManager::getVerificationResult ### Description Validates the base64-encoded verification token from the client-side widget using your secret API key. ### Parameters - **secretKey** (string) - Required - Your secret API key from the TrustCaptcha dashboard. - **verificationToken** (string) - Required - The base64-encoded verification token received from the client-side form submission. - **proxyOptions** (array) - Optional - Configuration for HTTP proxies, including 'proxy', 'username', and 'password'. ### Response Returns a `VerificationResult` object containing: - **verificationPassed** (boolean) - Indicates if the verification was successful. - **score** (float) - Bot score (lower values typically indicate human behavior). - **verificationId** (string) - Unique identifier for the verification. - **deviceFamily** (string) - Detected device family. - **browser** (string) - Detected browser. - **operatingSystem** (string) - Detected operating system. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.