Skip to main content

Integration with JavaScript and PHP

Learn how to integrate POWER CAPTCHA into your existing form with JavaScript and how to verify the token with PHP.

Once you have created and configured your API key, you can get started right away and integrate POWER CAPTCHA into your form.

The integration consists of two steps:

  1. Integration of the POWER CAPTCHA widget into your form
  2. Verification of the token after the form has been submitted

Integration into your form

Add JavaScript

Add our JavaScript to the page where the form is displayed:

<script src="https://cdn.power-captcha.com/v1/power-captcha-1.2.8.min.js" type="text/javascript" defer></script>

The JavaScript can be placed either in the <head> section or at the end of the page (before the </body> element).

Integrate the widget

Add the following <div> element within the form you want to protect and replace the placeholders in the data-pc-api-key and data-pc-client-uid attributes. The POWER CAPTCHA widget is displayed within the <div> element.

<form>
     ...
     <div data-pc-api-key="<apiKey>"
          data-pc-client-uid="<uniqueClientId>">
     </div>
     ...
</form>
Replace placeholder <apiKey>

The placeholder <apiKey> must be replaced with your API key.

Replace placeholder <uniqueClientId>

The placeholder <uniqueClientId> must be replaced with a dynamic value that uniquely identifies the client. For example, this can be the IP address of the client. It is important that the exact same value is also passed during the token verification.

Here is an example how the client ID can be generated using the IP address in PHP:

data-pc-client-uid="<?php echo hash('sha256', $_SERVER['REMOTE_ADDR']); ?>"
Using a reverse proxy

If your website runs behind a reverse proxy, $_SERVER['REMOTE_ADDR'] may not return the IP address of the client. Instead, depending on the configuration of the proxy, the client's IP address is sent in specific headers, often in X-Forwarded-For or X-Real-IP. In PHP, these headers can be read with $_SERVER['HTTP_X_FORWARDED_FOR'] or $_SERVER['HTTP_X_REAL_IP'].

Additional protection of an input field (optional, Enterprise license only)

If you have an Enterprise plan, you can secure an input field (e.g. user name / email address) with POWER CAPTCHA for additional protection. This requires the input field to be marked with the attribute data-pc-user. This allows our JavaScript to detect which field should be protected. Example:

<input name="username" type="text" required data-pc-user="" />

Please note that during token verification, the value of the input field must be provided unmodified.

Example login form with PHP and HTML

A simple login form that is protected with POWER CAPTCHA for example could look like this:

<form method="post" action="submit.php">
    <label for="username">Username:</label><br />
    <input type="text" id="username" name="username" required data-pc-user="" /><br />
    <label for="password">Password:</label><br />
    <input type="password" id="password" name="password" />
    <div data-pc-api-key="<apiKey>"
         data-pc-client-uid="<?php echo hash('sha256', $_SERVER['REMOTE_ADDR']); ?>">
    </div>
    <input type="submit" value="submit" />
</form>

Advanced settings and integration options

Additional configuration options and settings (e.g. Check mode / Hidden widget) can be found under Widget configuration.

Token verification in the backend

The widget automatically adds an hidden input field pc-token to your form. This field contains a token that you can verify in your backend.

This allows you to ensure that access has been checked and is authorized (e.g. if the captcha has been solved properly).

Check if the input field pc-token is empty

Before the actual verification, it is recommended to check if the input field pc-token exists and is not empty. If this is not the case, no token was generated before the form was submitted and thus the access is unauthorized.

<?php
if(!isset($_POST['pc-token']) || empty($_POST['pc-token'])) {
    // Cancel because token is missing
    die("No captcha token present."); 
    // Alternatively, you can also insert extended error handling here
}
// Continue with the token verification

Request to the verification API

Verification is done via our API (https://api.power-captcha.com/pcu/v1/verify). Several parameters, such as the field content from pc-token, must be sent to this endpoint as a JSON body via POST.

You can use cURL to call the API in PHP.

Initialize cURL

First, curl must be initialized. It is important that the X-API-Key field in the HTTP header includes your API key. Also, the Content-Type must be set to application/json.

$curl = curl_init('https://api.power-captcha.com/pcu/v1/verify');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'X-API-Key: <apiKey>', // Your API key
    'Content-Type: application/json'
));

The placeholder <apiKey> must be replaced with your API key.

Create JSON body

The JSON body with the parameters for the verification can be generated using an array and the PHP method json_encode.

$json_body = json_encode(
    array(
        'secret' => '<secretKey>', // Your secret key
        'token' => $_POST['pc-token'], // Token field value
        'clientUid' => hash('sha256', $_SERVER['REMOTE_ADDR']), // Unique client ID (same value as in the data-client-uid attribute)
        'name' => $_POST['username'] // Unchanged value of the field which was marked with ‘data-pc-user’ (optional, Enterprise license only)
    )
);

The placeholder <secretKey> must be replaced with your secret key.

Detailed information on the JSON structure and the parameters can be found under Verification of the token.

Send the request

You can now set the $json_body as a POST request in curl:

curl_setopt($curl, CURLOPT_POSTFIELDS, $json_body);

Then you can send the verification request to our API via curl_exec. The response is decoded via json_decode and is provided as an object.

$response = json_decode(
    curl_exec($curl)
);

Before evaluating the response, it is recommended to call curl_close to close the connection.

curl_close($curl);

Evaluate the response

The $response variable contains the result of the verification. The success field is primarily relevant which indicates whether the token verification was successful and whether the token is valid.

The result is checked with the following code. If $response->success == true, which means the token is valid, you can continue processing your form. Otherwise (token invalid or verification error), the execution is canceled.

if($response->success) {
    // Verification successful, token is valid
    // Insert your code for further evaluation of your form here
} else {
    // Cancel, because token invalid or error during verification
    die("Error: Captcha token invalid or verification failed.");
    // Alternatively, you can also insert extended error handling here
}

An unsuccessful verification ($response->success == false) can have several causes. You can find more information about this under Token verification.

Full code example

<?php
// Check if the input field pc-token is present and filled
if(!isset($_POST['pc-token']) || empty($_POST['pc-token'])) {
    // Cancel because token is missing
    die("No captcha token present."); 
    // Alternatively, you can also insert extended error handling here
}

// Initialize cURL
$curl = curl_init('https://api.power-captcha.com/pcu/v1/verify');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'X-API-Key: <apiKey>', // Your API key
    'Content-Type: application/json'
));

$json_body = json_encode(
    array(
        'secret' => '<secretKey>', // Your secret key
        'token' => $_POST['pc-token'], // Token field value
        'clientUid' => hash('sha256', $_SERVER['REMOTE_ADDR']), // Unique client ID (same value as in the data-client-uid attribute)
        'name' => $_POST['username'] // Unchanged value of the field which was marked with ‘data-pc-user’ (optional, Enterprise license only)
    )
);

// Set JSON body as POST request
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_body);

// Send request
$response = json_decode(
    curl_exec($curl)
);
curl_close($curl);

// Evaluate response
if($response->success) {
    // Verification successful, token is valid
    // Insert your code for further evaluation of your form here
} else {
    // Cancel, because token invalid or error during verification
    die("Error: Captcha token invalid or verification failed.");
    // Alternatively, you can also insert extended error handling here
}