Google reCAPTCHA 2.0 with Codeigniter Tutorial

shape
shape
shape
shape
shape
shape
shape
shape

Google reCAPTCHA implantation in codeigniter is pretty much easy and here’s the guide to get google reCAPTCHA in codeigniter.

Get Google reCAPTCHA Keys

First you have to generate your recaptcha keys by going to recaptcha admin panel and going to the bottom of the page and generate keys for reCAPTCHA 2.0.

Recaptcha2 keys Generation

 

Dowload Codeigniter Recaptcha Library

Download reCAPTCHA Library for Codeigniter from Here and extract the files. Now, Copy the file from libraries folder to your codeigniter application’s libraries directory and config content to config directory.

3. copy generated keys to config directory’s recaptcha.php

config / recaptcha.php

Create Form View

Now for the coding part we have to create out view (form.php).

[php]

<form action="cap_controller/g_recaptcha" method="post" >
<?php echo $widget;?>
<?php echo $script;?>
<?php echo form_error(‘g-recaptcha-response’); ?>

<input type="submit" value="Submit Form">
</form>

[/php]

 

Create Success View

Here’ our success view (success.php)

[html]
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Success</title>
</head>
<body>

<h1>Success!</h1>

</body>
</html>
[/html]

 

Controller Method and Form Validation Callback

Lets create a controller function and validation callback function for it

[php]

<?php // Support Mehtod Starts here

public function g_recaptcha() {
$this->load->library(‘recaptcha’);
$this->load->library(‘form_validation’);
$this->form_validation->set_rules(‘g-recaptcha-response’, ‘Captcha’, ‘callback_captcha_valid|required’);
$this->form_validation->set_error_delimiters(”, ”);

if ($this->form_validation->run() == FALSE) {
$data = array(‘widget’ => $this->recaptcha->getWidget(),
‘script’ => $this->recaptcha->getScriptTag());
$this->load->view("form");
}
else {
$this->load->view("success");
}
}
// Support Mehtod Ends here

// Formvalidation callback Mehtod Starts here
public function captcha_valid($str)
{
$recaptcha = $this->input->post(‘g-recaptcha-response’);

if (!empty($recaptcha)) {
$response = $this->recaptcha->verifyResponse($recaptcha);
if (!isset($response[‘success’]) and $response[‘success’] !== true) {
$this->form_validation->set_message(‘captcha_valid’, ‘Please Verify You Are Not A Robot.’);
return FALSE;
}
else{
return TRUE;
}
}
}
// Formvalidation callback Mehtod Ends here
[/php]

 

Output

and thats it! Here’s the output form is going to look like
Google reCAPTCHA Output in Codeigniter

Read tutorial if you want to display captcha using Codeigniter’s builtin library.

You can reach Waqas Yousaf through twitter @wiqi.

Leave a Reply

Your email address will not be published. Required fields are marked *