Category: CodeIgniter

Google reCAPTCHA 2.0 with Codeigniter Tutorial

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.

Read More
Waqas Yousaf January 5, 2018 0 Comments

Codeigniter Tricks and Hacks for Beginners

I have been using codeigniter for building small and medium level projects for quite some years now. There are few tweaks and tricks I would love to share with codeigniter enthusiasts to make their work bit easier.

 

HTML Email Templates

If you are building an newsletter system of email delivery method  for sending out different emails with html contents, this one is for you to get the job done seamlessly.

Create a folder in your views directory for email templates e.g. emailtemplates

Create email templates views and save them in the folder. Now we can approach the

[php]

public function send_mail() {

$template = ‘discounts’;

$this->load->library( ’email’ );

$this->email->from( ‘[email protected]’, ‘Some Receiver’ );

$this->email->to( ‘[email protected]’ );

$this->email->subject( ‘Message subject’ );

$this->email->message( $this->load->view( ‘emailtemplates/’ . $template , $data, true ) );

$this->email->send();

}

[/php]

$template is the view file in the emailtemplates folder which would be used to send emails and $data would be an array which would pass the parameters to the view.

 

The Second (Optional) parameter for the $this->uri->segment()

I use $this->uri->segment quite often to get the data from an url . If you haven’t tried it yet, let me explain it first.

If you have an url like http://helloworld.com/example/trick/ , Using

[php]

$this->uri->segment(1);

[/php]

would return you “example” and $this->uri->segment(2); would return you trick and so on.

By passing second parameter to segment method, you can set the default value for the parameter if no value is returned. You can use $this->uri->segment(2, ‘tweak’); and it would return ‘tweak’ even if there is no second segment of uri.

 

Remove Index.php from URL

Go to application > config > config.php

Change

[php] $config[‘index_page’] = "index.php"
[/php]

To

[php] $config[‘index_page’] = ""
[/php]

Open notepad

Paste the following code

[html] RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA] [/html]

Save the file as .htaccess in the root directory

You can replace last line of code if the above .htaccess file doesn’t work.

[php] RewriteRule ^(.*)$ index.php?/$1 [L,QSA] [/php]

 

 

Create  Custom Helper

First of all, a CI helper is not a class. It is a PHP file with multiple functions.

Open notepad and create a custom function “hello_world”.

[php] <?php
if ( ! function_exists(‘hello_world’))
{
function hello_world($var = ”)
{
$var = “Hello World! ”. $var;
return $var;
}
}
[/php]

Save this file to application/helpers/ directory. We shall call it “test_helper.php”

Using the Helper

This is how you’ll use it in your controller.

[php] $this->load->helper(test_helper’);
echo hello_world(‘John’);
[/php]

it would display

 Hello World! John

Read More
Waqas Yousaf December 6, 2017 0 Comments

Using Codeigniter’s Built-in Captcha with Form Validation

Why Use Codeigniter’s Built-in Captcha

Captchas are the images you use on your forms to keep bots off the bay. Codeigniter gives you a built-in captcha helper which you can use to generate some captchas. Bit confusing part for newbies is using codeigniter’s form validation with built-in captcha. Following is the working example of captcha generation and captcha validation in codeigniter.

Controller

Test.php

[php] <?php class Test extends CI_Controller { public function my_form(){ if($this->input->post()){
$this->load->library("form_validation");
$this->form_validation->set_rules(‘captcha’, ‘Captcha’, ‘callback_validate_captcha’); // Described below

if ($this->form_validation->run() == FALSE) {
$data[‘captcha’][‘image’] = $this->session->userdata("image");
}
else {
if(!$this->session->has_userdata(‘filename’))
redirect("Test/my_form");

if(file_exists(BASEPATH."../assets/captcha/".$this->session->userdata[‘filename’]))
unlink(BASEPATH."../assets/captcha/".$this->session->userdata[‘filename’]);

session_destroy();
print "So, You are not a robot!";
exit;
}
}
else{
$data[‘captcha’] = $this->_generate_captcha(); // Captcha Generated using custom function defined below
$session_data = array(‘captcha’ => $data[‘captcha’][‘word’],
‘image’ => $data[‘captcha’][‘image’],
‘filename’ => $data[‘captcha’][‘filename’] );

$this->load->library(‘session’);
$this->session->set_userdata($session_data);
}

$this->load->view(‘myform’, $data);
}

function _generate_captcha(){
$this->load->library(‘image_lib’);
$this->load->helper(‘captcha’);

$options = array(
‘img_path’ => ‘./assets/captcha/’, // this directory needs to be created to store generated image
‘img_url’ => base_url("assets/captcha"), // absolute path to directory.
‘img_width’ => 200,
‘expiration’ => 7200,
‘word_length’ => 8,
‘font_size’ => 30,
‘img_id’ => ‘Imageid’,
‘pool’ => ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’,

‘colors’ => array(
‘background’ => array(255, 255, 255),
‘border’ => array(255, 255, 255),
‘text’ => array(0, 0, 0),
‘grid’ => array(255, 40, 40))
);

$captcha = create_captcha($options);
return $captcha;
}

public function validate_captcha(){
$this->load->library(array("form_validation", "session"));
if(strtolower($this->input->post(‘captcha’)) != strtolower($this->session->userdata[‘captcha’])){
$this->form_validation->set_message(‘validate_captcha’, ‘Wrong captcha code’);
return false;
}
else{
return true;
}

}
}
?>

[/php]

View

myform.php

[html]

<form method="post">
<?php print $captcha[‘image’] ; print form_error(‘captcha’); ?>
<input name="captcha" placeholder="captcha" type="text">
<button type="submit">Validate Captcha</button>
</form>

[/html]
Download the compressed source code from here (mirror).

 

You can reach Waqas Yousaf through twitter @wiqi.

Read More
Waqas Yousaf December 5, 2017 3 Comments