Category: Web Development

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

Change WordPress Admin Panel’s Footer Text

Wordpress admin footer

Default wordpree admin footer text

Basically, Any web developer (including myself) takes a step further when it comes to branding.  With the following code, You can change the old and boring wordpress’ footer text and replace it  your own message.

Just go to functions.php of your theme and add the following code.

[php] function my_admin_footer () {
print "Your Company Name. <a href=’#’>Visit Website</a>";
}

add_filter(‘admin_footer_text’, ‘my_admin_footer’);
[/php]

Happy Experimenting!

 

[alert type=”warning” close=”true”]You’ll have to edit your theme’s functions file. If you dont know how to do it, Check out WordPress’ Guide on functions.php before proceeding.[/alert]

Read More
Waqas Yousaf April 4, 2017 0 Comments

Removing WordPress Menu Items with Single Click

As a web developer working on website, All I know is time is money and during developing a website, there is one thing I hated the most. “Deleting menu items”. You see when I want to remove a menu item in WordPress, I go to [highlight2]Appearance -> Menus[/highlight2]  in admin Panel and then I remove the items one by one by expanding the menu item and using Remove to delete single item. Imagine when you have to remove an entire submenu consisting dozens of links. This exercise becomes excoriating painful.

The Solution

Meet One Click Remove Menu

  1. Just download and install this tiny plugin
  2. A little trash can button would appear on the menu item.
  3. Just delete as many items you want to without expanding and finding tiny remove link .

Thats it, Menu Item deleted.

 

 

Read More
Waqas Yousaf March 27, 2017 0 Comments

Reset WordPress Password | Video Tutorial

Breif Intro into Resetting WordPress Password?

I usually need to reset wordpress passwords because I set temporary passwords and usually forget the password or misplace it. Also, there are tons of queries on different freelancing sites where clients post queries likes password hacked or password forgotten and I (“The Client”) need to recover this password. So, Resetting wordpress password is something every web developor and web master must know if you are into wordpress development.

Having said that the own pre-req for this tutorial is the access to wordpress website’s database manager which is phpmyadmin most of the times. You can access phpmyadmin from website’s Cpanel account.

Instructions

  1. [highlight3]Click phpmyadmin[/highlight3]
  2. [highlight2]Select your wordpress’ database. (if you don’t know your database name, then look it up into w-config.php file in root)[/highlight2]
  3. [highlight3]Open users table with prefix (which is rh_ in my case)[/highlight3]
  4. [highlight2]Look for the user you are going after and click edit[/highlight2]
  5. [highlight3]You’ll see some gibberish text written in user_pass field’s value column. Don’t worry. Just write in your new password in value column.[/highlight3]
  6. [highlight2]Click on the function drop down and select MD5[/highlight2]
  7. [highlight3]Click go[/highlight3]

This is it. You have just reseted the password of your wordpress website. I have created a tutorial video. Check it out below!

Watch Video Tutorial to Reset WordPress Password

 

You can reach Waqas Yousaf through twitter @wiqi.

Read More
Waqas Yousaf March 13, 2017 0 Comments

Beginner’s guide to HTML parsing or web scrapping with PHP

What is Web Scraping?

According to Wikipedia, Web scraping means “Web scraping (web harvesting or web data extraction) is a computer software technique of extracting information from websites.”
It simply means that you can copy data from other websites to show or store it on your website. Lets say you want to create a currency exchange calcular but you don’t want to input currency rates everyday on the website because its tedious work. You can purchase an API that can cost you around 500 USD or more or you can simply parse the currency values from any website that offers the same service. Simple as that.

Lets start with our today’s project

I’d extract information from state bank of Pakistan’s website to obtain US Dollar, GB Pound, Japanese Yen and Euro to Pakistani Rupee exchange rates.. In PHP, We need a library called PHP Simple HTML DOM Parser for this specific purpose. So lets head over to the website and download the library.

Source Code

[php] <?php require_once("simpledom.php"); // Loading the Library
$sUrl = file_get_contents("http://www.sbp.org.pk/"); //Enter the Webpage you want to parse
$sPageContent = new simple_html_dom();                       // Create New object
$sPageContent->load($sUrl);

$sTable = $sPageContent->find("form",0)->find("table",22);   // We’d Parse the Table No 23 within first form

$sUsd   = $sTable->find("table",0)->find("td",1)->plaintext;  // Get value from td 2 within table 1 in plain text
$sUsd   =  substr($sUsd,strpos($sUsd," ")+1);                 // Elemenate "USD " from the result

$sGbp   = $sTable->find("table",1)->find("td",1)->plaintext;  // Rinse and Repeat
$sGbp   =  substr($sGbp,strpos($sGbp," ")+1);

$sJpy   = $sTable->find("table",2)->find("td",1)->plaintext;
$sJpy   =  substr($sJpy,strpos($sJpy," ")+1);

$sEur   = $sTable->find("table",3)->find("td",1)->plaintext;
$sEur   =  substr($sEur,strpos($sEur," ")+1);

print "USD : ".$sUsd." – GBP : ".$sGbp." – JPY : ".$sJpy." – EUR : ".$sEur; // Here is the output
?>

[/php]

Here are the currency rates as off 22 July, 2016.

USD : 104.8398 – GBP : 138.3047 – JPY : 0.9938 – EUR : 115.4916

These Values are in Pakistani rupee and we can do whatever we want to with them. Hope you liked this tutorial. Here’s detailed manual.

You can reach Waqas Yousaf through twitter @wiqi.

Read More
Waqas Yousaf October 23, 2016 1 Comment

5 reasons to never use Flash on your website

Back in the 2000’s, When Flash came out first time with its smooth animations and sound support, It amazed me. I learnt Flash animations so that I can make my website cooler (I know but It was early 2k) but now days I recommend my clients to tick off the flash off their project list for following reasons

Stability and performance issues

Flash can make low end machines crippling slow because it guzzles resources like nothing else. Remember the browser crashes when you tried loading it in the past? Yeah.

Poor Usability

Who would like to encounter a 3-minute intro before browsing the website? Newsflash: No one has that much time. It also uses some effects (Mouse Roll over) that touch devices can’t understand, and try navigating a website with flash navigation, It’s the easiest recipe to hate your life, and don’t even get me started on that horrid UI/UX.

Better Alternatives

Developer use different JS libraries (JQuery, the most popular) to have great visual effects and animations on your website without straining your system. You can embed a video with HTML5 without any Flash these days. How cool is that?

Apple don’t and wont support it.

Apple devices don’t support flash. You won’t like to sacrifice a huge chunk of visitors to have some funky animations on your website. Would you?

And Finally,

Its disaster for SEO

Its internet age and Everything comes down to the SEO aka Search Engine Optimization. Search engines don’t recognize it. Simple. Search Engines loves to parse content. While flash can provide them some meta tags but It really effect the search engine optimization of your website in negative way.

Read More
Waqas Yousaf October 21, 2016 1 Comment

Create banned words list for WP titles

Why do you need a banned word list for titles?

Running a blog with multiple authors is such a nightmare. You got to deal with many things and on the top of the all you also got to look for the content being posted on the blogs.

You can either reduce the access level of bloggers and read all the content first by yourself and then publish it but it would take like forever and it would only add another task to your responsibilities. Then there is this way, in which you can add words you want to ban on the website and WordPress simply won’t let the bloggers add the titles with the banned words itself. Problem Solved.

How Do I Access Functions.php?

You’ll have to add this tiny function and a hook in your functions.php file which is stored in your theme’s directory.

CAUTION: BACKUP YOUR WEBSITE BEFORE DOING ATTEMPTING CHANGES. I WONT BE RESPONSIBLE FOR ANY MISHAP.

Code

[php] function wpb_title_bws($sTitle)
{
$BannedWords = "abc,xyz,omg"; // Banned words seperated by comma.
$BannedWords = explode(",", $BannedWords);

global $post;
$sTitle = $post->post_title;

foreach($BannedWords as $BannedWord)
{
if (stristr($sTitle, $BannedWord))
wp_die( __(‘Error: Remove the banned word "’. $BannedWord .’" in post title first!’) );
}
}

add_action(‘publish_post’, ‘wpb_title_bws’, 10, 1);
[/php]

 

You can reach Waqas Yousaf through twitter @wiqi.

Read More
Waqas Yousaf October 19, 2016 10 Comments

Generate PDF with PHP | PHP2PDF Tutorial

Why Generate PDF Files With PHP?

No site is completed with out generating PDF file reports today. There are plenty of open source free libraries to achieve this task but my personal favorite is FPDF class. I find it suitable for the task because of its simplicity, relatively smaller size and ease of use.

Just head to the fpdf.org to download a free copy of the library. Unzip it in your web directory and include “fpdf.php” and that’s about it.

Source Code

Below, You can find a pretty basic no bells and whistles code to make use of fpdf library and generate pdf file with php.

[php] <? require(‘fdpf/fpdf.php’); $ObjPdf = new FPDF(); $ObjPdf->AddPage();
$ObjPdf->SetTextColor(0,0,0);
$ObjPdf->SetFont(‘Arial’,’ B’,16);
$ObjPdf->Cell(30,20,’Please generate the pdf for me..’);
$ObjPdf->Output();
?>
[/php]

Result

Lets say you have saved the code in your local webserver’s root directory with file name “pdf.php” and you have library in a folder named “fpdf”, then you’ll open pdf.php in your browser, it will generate a pdf file.

Happy experimenting.

You can reach Waqas Yousaf through twitter @wiqi.

Read More
Waqas Yousaf October 16, 2016 0 Comments