How Google reCaptcha Application In Php Codeigniter

Google reCaptcha

reCAPTCHA is a free CAPTCHA service that helps digitize books, newspapers and radio broadcasts in the past. CAPTCHAs are usually used to avoid bots and spam attacks on a website.

Google inc. The largest internet company has made CAPTCHA services to facilitate the developers to secure / avoid spam attacks on websites built.

On this article we will applicate CAPTCHA into a PHP framework that is CodeIgniter. We only need 2 php files, create a new file named recaptcha.php in folder Application/config and write the following code:

<?php
defined('BASEPATH') OR exit('No direct script access allowed'); 
/*
* Recaptcha configuration settings
*
* recaptcha_sitekey: Recaptcha site key to use in the widget
* ‎
* recaptcha_secretkey: Recaptcha secret key which is used for communicating between your server to Google's
* ‎
* lang: Language code, if blank "en" will be used
* ‎
* recaptcha_sitekey and recaptcha_secretkey can be obtained from https://www.google.com/recaptcha/admin/
* ‎
* ‎ Language code can be obtained from https://developers.google.com/recaptcha/docs/language
* ‎
*/
$config['recaptcha_sitekey'] = "6Le89gYUAAAAAIENtNE52gZXRZbtLAOA7caL2vQY";
$config['recaptcha_secretkey'] = "6Le89gYUAAAAACwspqCQaB17kqgaUd1juP7eURwP"";
$config['lang'] = "id";

At the code on the top have 3 config is :
$config['recaptcha_sitekey'] $config['recaptcha_secretkey'] $config['lang']

To get sitekey and secretkey you can register at following link: https://www.google.com/recaptcha/admin select reCAPTCHA V2, then input your website domain. After that create a new file named Recaptcha.php in folder Application/libraries, write this following code:

<?php 
/*
* CodeIgniter NO Captcha ReCAPTCHA a.k.a reCAPTCHA Version 2.0 library
* ‎
* This library is based on official reCAPTCHA library for PHP
* ‎
* https://github.com/google/ReCAPTCHA *
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class ReCaptcha {
     private $signup_url = "https://www.google.com/recaptcha/admin";
     ‎private $_siteVerifyUrl = "https://www.google.com/recaptcha/api/siteverify?";
     ‎private $_secret, $_sitekey, $_lang;
     ‎private $_version = "php_1.0";
     ‎function __construct() {
     ‎     $this->ci = & get_instance();
     ‎     $this->ci->load->config('recaptcha', TRUE);
          ‎if ($this->ci->config->item('recaptcha_secretkey', 'recaptcha') == NULL || $this->ci->config->item('recaptcha_secretkey', 'recaptcha') == "") {
          ‎die("To use reCAPTCHA you must get an API key from <a href='" . $this->signup_url . "'>" . $this->signup_url . "</a>");
          ‎}
          ‎if ($this->ci->config->item('recaptcha_sitekey', 'recaptcha') == NULL || $this->ci->config->item('recaptcha_sitekey', 'recaptcha') == "") {
          ‎die("To use reCAPTCHA you must get an API key from <a href='" . $this->signup_url . "'>" . $this->signup_url . "</a>");
          ‎}
          ‎$this->_secret = $this->ci->config->item('recaptcha_secretkey', 'recaptcha');
          ‎$this->_sitekey = $this->ci->config->item('recaptcha_sitekey', 'recaptcha');
          ‎if ($this->ci->config->item('lang', 'recaptcha') == NULL || $this->ci->config->item('lang', 'recaptcha') == "") {
          ‎$this->_lang = 'en';
          ‎} else {
          ‎$this->_lang = $this->ci->config->item('lang', 'recaptcha');
          ‎}
}

/*
* Function to convert an array into query string
* ‎
* @param array $data Array of params
* ‎
* @return String query string of parameters
*/
private function _encodeQS($data) {
     $req = "";
     ‎foreach ($data as $key => $value) {
     ‎     $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
     ‎}
     ‎return substr($req, 0, strlen($req) - 1);
}

/**
* HTTP GET to communicate with reCAPTCHA server
* ‎
* @param string $path URL to GET
* ‎
* @param array $data Array of params
*
* ‎ @return string JSON response from reCAPTCHA server
*/
private function _submitHTTPGet($path, $data) {
     $req = $this->_encodeQS($data);
     ‎$response = file_get_contents($path . $req);
     ‎return $response;
‎}

‎ /**
*
* ‎Function for rendering reCAPTCHA widget into views
* ‎
* Call this function in your view * @return string embedded HTML
*/
‎public function render() {
     $return = '<div class="g-recaptcha" data-sitekey="' . $this->_sitekey . '"></div>
     ‎<script src="https://www.google.com/recaptcha/api.js?hl=' . $this->_lang . '" async defer>
     ‎</script>';
     ‎return $return;
}

/**
* Function for verifying user's input
* ‎
* @param string $response User's input
* ‎
* @param string $remoteIp Remote IP you wish to send to reCAPTCHA, if NULL $this->input->ip_address() will be called
* @return array Array of response
*/
public function verifyResponse($response, $remoteIp = NULL) {
     if ($response == null || strlen($response) == 0) {
     ‎// Empty user's input
     ‎$return = array( 'success' => FALSE, 'error_codes' => 'missing-input' );
     ‎}
     ‎$getResponse = $this->_submitHttpGet( $this->_siteVerifyUrl, array( 'secret' => $this->_secret, 'remoteip' => (!is_null($remoteIp)) ? $remoteIp : $this->ci->input->ip_address(), 'v' => $this->_version, 'response' => $response ) );
     ‎$answers = json_decode($getResponse, TRUE);
     ‎if (trim($answers ['success']) == true) {
     ‎// Right captcha!
     ‎$return = array( 'success' => TRUE, 'error_codes' => '' );
     ‎ } else {
     ‎// Wrong captcha!
     ‎$return = array( 'success' => FALSE, 'error_codes' => $answers['error-codes'] );
     ‎‎} return $return;
‎  }
‎}

Then we will running and testing our reCAPTCHA, create a new controller named Contact.php in folder Application/controllers and the following code is below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Contact extends CI_Controller {
    public function __construct() {
    ‎parent::__construct();
    ‎//load library
    ‎$this->load->library(array('recaptcha','form_validation'));
    ‎}
    ‎public function index() {
    ‎     $data = array( 'recaptcha_html' => $this->recaptcha->render() );
    ‎//set form validation
    ‎$this->form_validation->set_rules('username', 'Username', 'required');
    ‎$this->form_validation->set_rules('password', 'Password', 'required');
    ‎$this->form_validation->set_rules('g-recaptcha-response', '<strong>Captcha</strong>', 'callback_getResponseCaptcha');
    ‎//set message form validation
    ‎$this->form_validation->set_message('required', '{field} is required.');
    ‎$this->form_validation->set_message('callback_getResponseCaptcha', {field} {g-recaptcha-response} must filled. ');
    ‎if($this->form_validation->run() == TRUE) {
    ‎//if valid condition
    ‎}else{
    ‎$this->load->view('recaptcha');
    ‎ }
    ‎} public function getResponseCaptcha($str) {
    ‎$this->load->library('recaptcha');
    ‎$response = $this->recaptcha->verifyResponse($str);
    ‎if ($response['success']) { return true; } else {
    ‎$this->form_validation->set_message('getResponseCaptcha', '%s is required.' );
    ‎return false;
    ‎}
}
}

Create a new file named recaptcha.php in folder Application/views and write the following code:

<div class="container">
<form class="form-signin" accept="utf-8" action="<?php echo base_url() ?>contact">
<h2 class="form-signin-heading">Please sign in</h2>
‎<div class="form-group">
‎<label for="inputEmail" class="sr-only">Username</label>
‎<input type="text" name="nama" class="form-control" id="nama" placeholder="Masukkan Username Anda" value="<?php echo set_value('username') ?>" autocomplete="off">
‎<?php echo form_error('username'); ?>
‎</div>
‎<div class="form-group">
‎<label for="inputPassword" class="sr-only">Password</label>
‎<input type="password" name="nama" class="form-control" id="nama" placeholder="Masukkan Username Anda" value="<?php echo set_value('password') ?>" autocomplete="off">
‎<?php echo form_error('password'); ?>
‎</div>
‎<div class="form-group">
‎<label>Recaptcha</label>
‎<?php echo $recaptcha_html;?>
‎<?php echo form_error('g-recaptcha-response'); ?>
‎</div>
‎<div class="checkbox">
‎<label>
‎<input type="checkbox" value="remember-me"> Remember me
‎</label>
‎</div>
‎<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
‎</form>
‎</div>


Now run and test your project in localhost
Related Post
close