Skip to content

PHP CAPTCHA Integration

The following tutorial will guide you on how to integrate the TrustCaptcha CAPTCHA solution into your PHP backend to retrieve and evaluate the CAPTCHA verification result.

You should have already completed the following steps before you start with CAPTCHA validation in PHP backend.

  1. Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing PHP project: You need a PHP project in which you want to integrate TrustCaptcha.

  5. Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.


Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your PHP backend.

You can find the source code of our PHP CAPTCHA integration on Github.

To use the TrustCaptcha PHP library, you first need to add the corresponding dependencies to your project.

Terminal window
composer require trustcomponent/trustcaptcha-php

You can find our TrustCaptcha PHP package on Packagist.

In the next step, retrieve the CAPTCHA result from our servers.

If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need the secret-key from your CAPTCHA. You can find your secret key in the dashboard of your CAPTCHA.

Now use the CaptchaManager class of our PHP integration to retrieve the verification result from our servers.

// Retrieving the verification result
$verificationResult = null;
try {
$verificationResult = CaptchaManager::getVerificationResult("<your_secret_key>", $verificationToken);
} catch (Exception $e) {
// Fetch verification result failed - handle error
}

Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the result validation overview.

// Act on the verification result
if (!$verificationResult->verificationPassed || $verificationResult->score > 0.5) {
echo "Verification failed or bot score > 0.5 – possible automated request.";
}

If your PHP application is running behind an HTTP proxy, you can configure the TrustCaptcha PHP library to send the verification request through that proxy. The CaptchaManager::getVerificationResult() method accepts an optional third parameter $proxyOptions.

Supported proxy options:

  • proxy Full proxy URL, for example: http://proxy.example.com:8080 (required when using a proxy)
  • username Proxy username (optional, only needed if your proxy requires authentication)
  • password Proxy password (optional, only needed if your proxy requires authentication)

If you do not use a proxy, simply call getVerificationResult($secretKey, $verificationToken) as shown in the basic example.

Example: proxy without authentication

$secretKey = '<your_secret_key>';
$verificationToken = '<verification_token_from_the_widget>';
$proxyOptions = [
'proxy' => 'http://proxy.example.com:8080',
];
try {
$verificationResult = CaptchaManager::getVerificationResult(
$secretKey,
$verificationToken,
$proxyOptions
);
} catch (Exception $e) {
// Fetch verification result failed - handle error
}

Example: proxy with username/password

$secretKey = '<your_secret_key>';
$verificationToken = '<verification_token_from_the_widget>';
$proxyOptions = [
'proxy' => 'http://proxy.example.com:8080',
'username' => 'myProxyUser',
'password' => 'myProxyPassword',
];
try {
$verificationResult = CaptchaManager::getVerificationResult(
$secretKey,
$verificationToken,
$proxyOptions
);
} catch (Exception $e) {
// Fetch verification result failed - handle error
}

You can reuse the same evaluation logic as in the example above ($verificationResult->verificationPassed, $verificationResult->score, etc.); only the way the result is fetched changes when a proxy is used.


The following example shows a possible implementation of TrustCaptcha in a PHP backend.

In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the PHP backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.

Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.

The complete example including source code can be found on Github.

<?php
require_once __DIR__ . '/vendor/autoload.php';
use TrustComponent\TrustCaptcha\CaptchaManager;
$message = "";
$verificationResult = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$message = $_POST['message'] ?? '';
$verificationToken = $_POST['tc-verification-token'] ?? '';
// Retrieving the verification result
try {
$verificationResult = CaptchaManager::getVerificationResult("<your_secret_key>", $verificationToken);
} catch (Exception $e) {
// Fetch verification result failed - handle error
throw new RuntimeException($e);
}
// Act on the verification result
if (!$verificationResult->verificationPassed || $verificationResult->score > 0.5) {
$message = "Verification failed or bot score > 0.5 – possible automated request.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trustcaptcha Testsystem</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<script src="https://cdn.trustcomponent.com/trustcaptcha/2.1.x/trustcaptcha.umd.min.js"></script>
</head>
<body class="py-5">
<div class="d-flex justify-content-center">
<div class="w-100" style="max-width: 640px;">
<h1>PHP</h1>
Try PHP<br />
<form action="/" method="post">
<div class="mb-3">
<label for="messageInput" class="form-label">Message</label>
<textarea class="form-control" id="messageInput" name="message" placeholder="Write a message" rows="3"><?= htmlspecialchars($message) ?></textarea>
</div>
<div class="mb-3">
<trustcaptcha-component
id="trustcaptchaComponent"
sitekey="<your_site_key>"
language="en"
theme="light"
></trustcaptcha-component>
</div>
<div class="d-grid gap-2">
<button class="btn btn-success" id="submitButton" disabled>Post new message</button>
</div>
</form>
<?php if ($verificationResult): ?>
<div class="alert alert-success mt-3" role="alert">
<strong>Message: </strong><?= htmlspecialchars($message) ?><br>
<strong>Passed: </strong><?= $verificationResult->verificationPassed ? 'true' : 'false' ?><br>
<strong>Reason: </strong><?= htmlspecialchars($verificationResult->reason) ?><br>
<strong>Score: </strong><?= htmlspecialchars($verificationResult->score) ?>
</div>
<?php endif; ?>
</div>
</div>
</body>
<script>
<!-- example, unused in this sample -->
function resetCaptcha() {
const trustcaptchaComponent = document.getElementById('trustcaptchaComponent');
trustcaptchaComponent.reset();
}
const trustcaptchaComponent = document.getElementById('trustcaptchaComponent');
trustcaptchaComponent.addEventListener('captchaSolved', (event) => {
console.log('Verification token:', event.detail);
const submitButton = document.getElementById('submitButton');
submitButton.disabled = false;
});
trustcaptchaComponent.addEventListener('captchaFailed', (event) => {
console.error(event.detail);
});
</script>
</html>

Once you have integrated the TrustCaptcha widget into your frontend and the CAPTCHA result validation into your backend, you can use TrustCaptcha to its full extent. However, we still recommend the following additional technical and organizational measures:

  • Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.

  • Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.

  • Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.

  • Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.