· 5 years ago · Mar 28, 2020, 11:20 AM
1<?php
2class Captcha
3{
4 private $sitekey;
5 private $secretkey;
6 private $ip;
7 const RECAPTCHA_API_URL = 'https://www.google.com/recaptcha/api/siteverify';
8
9 public function __construct(string $sitekey, string $secretkey)
10 {
11 $this->key = $sitekey;
12 $this->secretkey = $secretkey;
13 }
14
15 private function getUserIp() : ?string
16 {
17 return $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_X_CLIENT_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? null;
18 }
19
20 private function post(string $url, array $data)
21 {
22 $curl = curl_init();
23 curl_setopt_array($curl, array(
24 CURLOPT_URL => $url,
25 CURLOPT_RETURNTRANSFER => true,
26 CURLOPT_POST => true,
27 CURLOPT_FAILONERROR => false,
28 CURLOPT_FOLLOWLOCATION => true,
29 CURLOPT_POSTFIELDS => http_build_query($data)
30 ));
31
32 $response = json_encode(curl_exec($curl));
33 curl_close($curl);
34
35 return $response;
36 }
37
38 private function verify(string $str)
39 {
40 $result = $this->post(
41 self::RECAPTCHA_API_URL,
42 $data = [
43 'secret' => $this->secretkey,
44 'response' => $str,
45 'remoteip' => $this->getUserIp(),
46 ]
47 );
48
49 return isset($result->success) && $result->success === true;
50 }
51}
52?>