summaryrefslogtreecommitdiff
path: root/includes/classes/CloudflareTurnstile.php
blob: 4c4deb1b366eca4b4dbfb20c1e81556b55d81938 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

class CloudflareTurnstileValidator {
	private $secretKey;
	private $verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';

	public function __construct($secretKey) {
		$this->secretKey = $secretKey;
	}

	public function validate($responseToken, $remoteIp = null) {
		// Prepare POST data
		$data = [
			'secret' => $this->secretKey,
			'response' => $responseToken,
		];

		if ($remoteIp) {
			$data['remoteip'] = $remoteIp;
		}

		// Initialize cURL
		$ch = curl_init($this->verifyUrl);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);

		// Execute request
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		curl_close($ch);

		$ret = [];

		// Decode JSON response
		$result = json_decode($response, true);

		if (!$result) {
			$ret = [
				'success' => false,
				'error_codes' => [ 'Invalid response from verification server ('.$httpCode.')' ],
			];
		} else {
			$ret = [
				'success' => $result['success'],
				'timestamp' => $result['challenge_ts'] ?? null,
				'hostname' => $result['hostname'] ?? null,
				'error_codes' => $result['error-codes'] ?? [],
			];
		}

		return $ret;
	}
}

// Example usage:
/*
$validator = new TurnstileValidator('YOUR_SECRET_KEY_HERE');
$result = $validator->validate($_POST['cf-turnstile-response'], $_SERVER['REMOTE_ADDR']);

if ($result['success']) {
	echo "Verification successful!";
} else {
	echo "Verification failed: " . implode(', ', $result['error_codes']);
}
*/