Cara Memasang Google Recaptcha di Framework CodeIgniter
Facebook Twitter Google +
Kamis, 06 Juli 2017 Jam 11:24:33

reCAPTCHA adalah sebuah layanan CAPTCHA gratis yang membantu proses digitalisasi buku, koran dan siaran radio pada masa lalu. ... CAPTCHA biasanya digunakan untuk menghindari serangan bot dan spam pada suatu website .

 

Perusahaan internet terbesar yaitu google, telah membuat layanan CAPTCHA untuk mempermudah para developer untuk mengamankan / menghindari dari serangan spam pada website yang dibangun.

 

Pada kesempatan kali ini kita akan membuat / mengaplikasikan CAPTCHA buatan google tersebut kedalam sebuah framework PHP yang cukup populer diindonesia, yaitu CodeIgniter.

 

Pada pengaplikasian CAPTCHA google ini kita hanya membutuhkan 2 file php, langsung saja.

 

Buat sebuah file baru bernama recaptcha.php di folder Application/config berikut source code yang kita tuliskan:

 


 */
$config['recaptcha_sitekey'] =  "6Le89gYUAAAAAIENtNE52gZXRZbtLAOA7caL2vQY";

$config['recaptcha_secretkey'] = "6Le89gYUAAAAACwspqCQaB17kqgaUd1juP7eURwP"";

$config['lang'] = "id";


Pada source code diatas perlu diketahui yaitu ada 3 buah config variabel, yaitu:

 

$config['recaptcha_sitekey']

$config['recaptcha_secretkey']

$config['lang']

 

Untuk mendapatkan sitekey dan screetkey Anda bisa mendaftar di link berikut ini:

 

https://www.google.com/recaptcha/admin

 

Terus pilih reCAPTCHA V2, kemudian masukan domain website Anda, setelah itu Anda akan mendapatkan sitekey dan screetkey dari google.


Setelah itu kita buat file baru bernama Recaptcha.php di folder Application/libraries, berikut source codenya:

 

<?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;
    }
}


Setelah itu kita akan coba test / uji reCAPTCHA kita, buatlah sebuah controller baru bernama Contact.php di folder Application/controllers, berikut source codenya:

 


 * @since    : 2017
 * @license  : https://bismalabs.co.id/
 */
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', 'Captcha', '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} harus diisi. ');
        if($this->form_validation->run() == TRUE)
        {
            
            //kondisi jika recaptcha dan form validasi terpenusi

        }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;
        }
    }
}

       


Setelah itu buat lagi sebuah file baru bernama recaptcha.php di folder Application/views, berikut source codenya:

 

    <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> 

 

Sekarang coba jalankan project Anda di http://localhost/folder_project/contact

Semoga Bermanfaat :)

Article ini telah dibaca sebanyak 4233 kali
#CodeIgniter # PHP # Google reCaptcha

Sekilas Tentang Penulis

Fika Ridaul Maulayya
Chief Technology Officer at Bisma Labs, seorang yang gemar mempelajari tentang dunia pemrogramman dan teknologi

SHARE

Facebook Twitter Google +

COMMENTS

blog comments powered by Disqus