There are a lot of shitty written tutorials about captcha here and I your savior decided to write you one universal captcha which will work everywhere in your code whenever you need.
1. Go to backend and create a new PHP file named Captcha.php
Register your captcha and domain on https://google.com/recaptcha
Set secret and public key inside
$this->key = 'your_public_key';
$this->secret = 'your_secret_key';
2. Inside backend/functions.php add the following code next to other require codes you have at the top.
3. Now the actual usage:
Wherever you want to call captcha include it with something like:
Then, you check if captcha is correct where your POST request is set
For example:
4. This is your HTML part for the form:
captcha <div> is stored inside html() method which you can call like:
The final output of the captcha:
1. Go to backend and create a new PHP file named Captcha.php
Register your captcha and domain on https://google.com/recaptcha
Set secret and public key inside
$this->key = 'your_public_key';
$this->secret = 'your_secret_key';
<?php
/*
* The only reCaptcha v2 tutorial you will ever need for TorrentTrader
*
* @package recaptcha_v2_torrenttrader
* @license GPLv3
* @author Shadows
* @version 1.0
*/
class Captcha
{
private $key;
private $secret;
private $response;
private $captcha;
public function __construct()
{
$this->key = 'your_public_key';
$this->secret = 'your_secret_key';
}
public function response()
{
$this->captcha = $_POST['g-recaptcha-response'];
$this->response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $this->secret . '&response=' . $this->captcha);
return $this->response = json_decode($this->response);
}
public function html()
{
return '<script type="text/javascript" src="https://www.google.com/recaptcha/api.js"></script>
<div class="g-recaptcha" data-theme="light" data-sitekey="' . $this->key . '"></div>';
}
}
2. Inside backend/functions.php add the following code next to other require codes you have at the top.
require dirname(__FILE__).'/Captcha.php';3. Now the actual usage:
Wherever you want to call captcha include it with something like:
$captcha = new Captcha();Then, you check if captcha is correct where your POST request is set
For example:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if ($captcha->response()->success)
{
// If captcha is solved.
}
else
{
// captcha is incorrect.
}
}
4. This is your HTML part for the form:
captcha <div> is stored inside html() method which you can call like:
echo $captcha->html();
or
<?= $captcha->html(); ?>
or
<?php echo $captcha->html(); ?>
The final output of the captcha:
<?php
$captcha = new Captcha();
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if ($captcha->response()->success)
{
echo 'You have completed captcha! YAY'
}
else
{
echo 'Go away BOT!';
}
}
?>
<form method="post">
<?= $captcha->html(); ?>
<button type="submit">Submit</button>
</form>