03 กุมภาพันธ์ 2566

PHP Cloudflare Turnstile

Turnstile is Cloudflare’s smart CAPTCHA alternative.

https://www.cloudflare.com/products/turnstile/

<?php
if (isset($_POST["cf-turnstile-response"])) {

    $captcha = $_POST['cf-turnstile-response'];
    $secretKey = "__Secret_Key__";
    $ip = $_SERVER['REMOTE_ADDR'];
    $url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
    $data = array('secret' => $secretKey, 'response' => $captcha, 'remoteip' => $ip);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $curlData = curl_exec($curl);
    curl_close($curl);
    
    $result = json_decode($curlData, true);
    
    if (intval($result["success"]) == 1) {
        echo "success";
        exit();
    } else {
        echo "error";
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Test Turnstile</title>
        <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
    </head>
    <body>
        <form method="POST" action="">
            <div>
                <!-- The following line controls and configures the Turnstile widget. -->
                <div class="cf-turnstile" data-sitekey="__Site_Key__" data-theme="light"></div>
                <!-- end. -->
            </div>
            <button  type="submit">Sign in</button>
        </form>
    </body>
</html>