Category: PHP

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

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

PHP Date and Time Reference | Cheatsheet

Why Do I Need PHP Date And Time Refernce?

Need for a PHP date and time reference arose when I was working on a blog and I had to check for the date and time functions every now and then. Let me admit something here. Nobody is a perfect programmer. We usually need references and cheatsheets to get out word done quickly. PHP like every other maintained programming language has like thousands if not millions of function names and parameters.
I cannot remember all the functions and classes for a specific task. I simply needed an online reference for PHP date time functions so that I dont have to go snoop around like 30 pages to find one itsy bitsy function.

date() Function

date() month pretty much handy while you are dealing with date/time functionality in PHP. for example

[php]print date("d-m-Y");[/php]
Output:  05-07-2016

this function would print current date in simple day-month-year format as shown above.

[php]date("h:i:s")[/php]
Output:  10:37:58

and this function would print time in mundane hour:minutes:seconds format as given below

You can also add other details like day and am/pm as well.

[php]print date("l d-m-Y h:i A");[/php]
Output:  Tuesday 05-07-2016 10:44 AM

If you wanted to check if a date exists or not, you can use checkdate(‘m’,’d’,’Y’) function
It works something like this

[php]$check = (checkdate(20, 10, 1985)) ? "TRUE" : "FALSE";
print $check; [/php]
Output:  FALSE

It would print false as output because 20th doesnt exist. or does it?

date_create() Function

There’s a date_create() function to create an date object so date/time funcsionality.

[php]$date = date_create();
var_dump($date);
[/php]
Output:  object(DateTime)[1]
public 'date' => string '2016-07-02 09:06:20' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Paris' (length=12)

 

date_diff() Function

date_diff() is a function that gives out the interval between two given dates.

[php]

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff = date_diff($date1,$date2);
var_dump($diff) ;
[/php]

Output:  object(DateInterval)[3]
public 'y' => int 0
public 'm' => int 8
public 'd' => int 27
public 'h' => int 0
public 'i' => int 0
public 's' => int 0
public 'weekday' => int 0
public 'weekday_behavior' => int 0
public 'first_last_day_of' => int 0
public 'invert' => int 0
public 'days' => int 272
public 'special_type' => int 0
public 'special_amount' => int 0
public 'have_weekday_relative' => int 0
public 'have_special_relative' => int 0

 

date_format() Function

date_format() is a function to format date as provided.

[php]$date=date_create("1999-07-30");
print date_format($date,"d-m-Y");[/php]
Output:  30-07-1999

 

time() Function

time() function gives you current epoch or unix time.

[php]print time();[/php]
Output:  1467707548

 

gmdate() Function

You can format the output in human reabible using gmdate() function

[php] $unixTime = time();
print gmdate(‘l h:i:s d-m-Y’, $unixTime);
[/php]
Output:  Tuesday 10:09:13 05-07-2016

 

strtotime Function

function returns relative time,string unix timestamp format.

[php]print strtotime("now");
print strtotime("12 December 2009");
print strtotime("+8 hours");
print strtotime("+1 week");
print strtotime("+1 week 3 days 7 hours 5 seconds");
print strtotime("next Friday");[/php]

 

Output:  1260572400
1467738028
1468314028
1468598433
1467928800

 

Relative Time Function

Here’s one script I have found on github to find relative time.

Just copy above above function and then you can use it in your program like

[php]print time2str(strtotime("10-june-2016"));[/php]

And the output would be something like this

Output:  4 weeks ago

 

You can reach Waqas Yousaf through twitter @wiqi.

Read More
Waqas Yousaf August 12, 2016 1 Comment