Tuesday, October 29, 2013

How To Implement Pagination In Codeigniter ion_auth library?

This is how I implemented pagination customized using bootstrap styles in Codeigniter ion_auth Library.
	function display_user()
		$this->data['title'] = "Display User";

		if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
			redirect('auth', 'refresh');

		$config = array();
		$config["base_url"] = base_url() . "auth/display_user/";;
		$config['total_rows'] = $this->ion_auth->users()->num_rows();
		$config['per_page'] = '30';

		//pagination customization using bootstrap styles
		$config['full_tag_open'] = ' <ul class="pagination pull-right">';
		$config['full_tag_close'] = '</ul><!--pagination-->';
		$config['first_link'] = '&laquo; First';
		$config['first_tag_open'] = '<li class="prev page">';
		$config['first_tag_close'] = '</li>';

		$config['last_link'] = 'Last &raquo;';
		$config['last_tag_open'] = '<li class="next page">';
		$config['last_tag_close'] = '</li>';

		$config['next_link'] = 'Next &rarr;';
		$config['next_tag_open'] = '<li class="next page">';
		$config['next_tag_close'] = '</li>';

		$config['prev_link'] = '&larr; Previous';
		$config['prev_tag_open'] = '<li class="prev page">';
		$config['prev_tag_close'] = '</li>';

		$config['cur_tag_open'] = '<li class="active"><a href="">';
		$config['cur_tag_close'] = '</a></li>';

		$config['num_tag_open'] = '<li class="page">';
		$config['num_tag_close'] = '</li>';


		$the_uri_segment = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$config['uri_segment'] = $the_uri_segment;

		//list the users
		$this->data['users'] = $this->ion_auth->offset($this->uri->segment($the_uri_segment))->limit($config['per_page'])->users()->result();

		foreach ($this->data['users'] as $k => $user)
			$this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();

		$this->data['links'] = $this->pagination->create_links();
		//set the flash data error message if there is one
		$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

		$this->data['include'] = 'auth/display_user';
		$this->_render_page('auth/template', $this->data);

 <?php echo $links;?>
//output the proper pagination links styled with twitter bootstrap css

Monday, October 28, 2013

How To Read JSON Data Response Using PHP?

This tutorial will teach you how to decode JSON objects using PHP. Reading a JSON is just as easy and it just has to output a json string and save it to variable(for instance $json_data), And now pass $json_data to json_decode function and read/parse.
Example JSON Response
$json_data = '{
      "stat": "ok",
      "profile": {
        "providerName": "testing",
        "identifier": "http://testing.com/58263223",
        "displayName": "testing 1",
        "preferredUsername": "testing 2",
        "name": {
          "formatted": "testing"
        "url": "http://testing.com/testing/",
        "photo": "https://securecdn.testing.com/uploads/users/5826/3223/avatar32.jpg?1373393837",
        "providerSpecifier": "testing"
PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type. The following examples shows how PHP can be used to decode JSON objects:
Alternative 1 (returns object format)
$data = json_decode($json_data);
echo $data->profile->displayName; // outputs testing 1
echo $data->profile->preferredUsername;// outputs testing 2
Alternative 2 (returns array format)
$data = json_decode($json_data, true);
$preferredUsername = $data['profile']['preferredUsername'];
$displayName = $data['profile']['displayName'];
Ref: http://stackoverflow.com/a/17865683

Wednesday, October 23, 2013

CodeIgniter Encryption Keys

Can be used for any other 256-bit key requirement.
Ref: http://randomkeygen.com/

Tuesday, October 22, 2013

How To Get Last segment From URL In Codeigniter?

I need to get the value of last URI / URL segment in Codeigniter today and I came up with this easy solutions. It permits you to retrieve a last segment from the URI. ALL three alternative works like charm.
Alternative 1:
$last = end($this->uri->segments); 
//Where, segments is a class variable.
Alternative 2:
$last = end($this->uri->segment_array());
Alternative 3:
$total = $this->uri->total_segments();
$last = $this->uri->segment($total);

Monday, October 21, 2013

Prompting a User to Save Changes Before Leaving a Page Using jQuery

The first step is to know when the form is ‘dirty’ i.e. when a user has made any change to the form that has not been saved. There are a various ways to know that a form is dirty, but I chose to declare a global variable called ‘isDirty’.
var isDirty = false;
$(document).ready(function() {
//save all the input values to check later
$('#myform input').each(function() {
  $(this).data('original', $(this).val());

 $(window).bind('beforeunload', function(){
   //to update the dirty flag when there is a different form values 
   $('#myform input').each(function() {
   if ($(this).data('original') != $(this).val()) {
    isDirty = true;
  if (isDirty) {
   return 'You haven\'t saved your changes.';

This method will detect if the user has made any changes in the form and alert the confirmation dialog. In this way, you can protect a user from leaving the page if there is change in the form.

There are many other ways to achieve this. If you know any other way to achieve this, do share here.

Ref: http://www.prosoxi.com/2012/06/21/jquery-method-to-prompt-a-user-to-save-changes-before-leaving-page/

Tuesday, October 15, 2013

Bootstrap 3 input-append fix

Remove input-prepend and input-append for singular `.input-group`. The classes have changed for the elements within, and require a bit more markup to use buttons:
- Use `.input-group` as the parent class around the input and addon.
- For text based prepends/appends, use `.input-group-addon` instead of `.addon`.
- For button prepends/appends, use `.input-group-btn` and place your `.btn` within that element.
<div class="container">
  <div class="row">
    <div class="col-sm-3 col-xs-12 col-lg-3">
      <form class="form-search">
          <div class="input-group">
              <input type="text" class="form-control " placeholder="Text input">
              <span class="input-group-btn">
                  <button type="submit" class="btn btn-search">Search</button>
Source: http://stackoverflow.com/a/18358354

Monday, October 14, 2013

How To Integrate Codeigniter Form Validation Library and jQuery AJAX ?

In this tutorial, I am showing how to integrate Codeigniter form validation library and jQuery Ajax.

We are using Codeigniter Form Validation class to validate the input fields. If the error exists, form values will not be saved and will display proper validation errors. jQuery and Ajax is used to avoid a full page refresh resulted from a form validation. You can find complete source code ready to be used below. I have used the form directly from codeigniter form validation example.

/* controller/example.php*/

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Example extends CI_Controller{

function index()
		$data['include'] = 'jquery_ci_form';
		$this->load->view('template', $data);		
	function jquery_save()
		$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
		$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
		$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		if ($this->form_validation->run() == FALSE)
			echo json_encode(array('st'=>0, 'msg' => validation_errors()));
			$username = $this->input->post('username');
			$password = $this->input->post('password');
			$email = $this->input->post('email');
			//...save values to database 
			echo json_encode(array('st'=>0, 'msg' => 'Successfully Submiited'));
/* view/template.php */
<?php $this->load->view('includes/header'); ?>
<?php //$this->load->view('includes/sidebar'); ?>
<?php $this->load->view($include); ?>
<?php $this->load->view('includes/footer'); ?>
/* view/jquery_ci_form.php */
<?php echo form_open('example/jquery_save', array('id'=>'frm')); ?>

<div id="validation-error"></div>

<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

<div><input type="submit" value="Submit" /></div>

/* assets/js/custom.js*/
$(document).ready(function() {
	$.post($('#frm').attr('action'), $('#frm').serialize(), function( data ) {
	if(data.st == 0)
		if(data.st == 1)
	}, 'json');
	return false;			


Tuesday, October 8, 2013

How To Remove Query String From URL in PHP?

Today I needed to remove the query string or parameter from the URL. I found this quick function which does exactly what i needed i.e remove query string from URL.
function remove_qs_key($url, $key) {
 return preg_replace(‘/(?:&|(\?))’ . $key . ‘=[^&]*(?(1)&|)?/i’, “$1″, $url);
For example, if your URL was this:
  $url = http://example.com/test/index?id=55&template=view&format=pdf
  $key = 'format';
The above function would return:
  echo remove_qs_key($url, $key);
 //output: http://example.com/test/index?id=55&template=view
All I needed to do was provide the URL and the key to remove -- so easy and simple :)
Thanks to http://davidwalsh.name/php-remove-variable

Monday, October 7, 2013

How to Generate Pdfs or Images Using Phantomjs in Codeigniter?

PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG." Let's see what PhantomJS can do to fulfil my task requirements:

It renders web pages the same as the browsers which uses Webkit, such as Google Chrome or Apple Safari.
It supports SVG.
It has JavaScript API which lets me change the web page as needed.
It has a cookie API which solves the user authentication issue.
It can output the rendering page in a few formats which includes PDF.

You can easily find one helper file called "PhantomJS Wrapper Helper For CodeIgniter" in the internet which almost solves problem. Read and download it from here.

I spent almost 2 days to make this work. I followed all the steps and I was able to run it successfully via command line but not via PHP script. When I tried to generate pdfs via PHP, it didn't worked at all. I searched a lot in Google and found many suggested suggestions but none of it worked.

I then tried in the live server, it work straight away. That was very strange. :)

I knew that problem was about permission issues.

In my localhost environment, I added sudo -u anup in exec() function and it worked. :)

Don't forget to use escapeshellcmd () function as well, other wise it won't work if you have query strings in your URL.
$url = escapeshellcmd($url);
/*escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator. */

Replace the original helper file with following helper file. You can find helper file under "application/helpers/phantomjs_helper.php"
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('rasterize_wrapper'))
 function rasterize_wrapper($url='', $output=''){
   if($url=='' || $output=='')
       show_error('URL or Output file name not defined correctly'); 
       log_message('error','rasterize_wrapper: not initialized');

        $url = escapeshellcmd($url);  // ADDED BY ME

 //using exec here, so be resposible and make sure you validate both the $output and $url above in the above function itself. I have not
 //Assuming that phantomjs's path has been included in you $PATH var

   exec('sudo -u anup phantomjs '.realpath('assets/js').'/rasterize.js '.$url.' '.realpath('assets/pdfs').$output,$output_status, $return_status); // SUDO -U USERNAME ADDED BY ME

 if($return_status=='0'){ return true;}
 return false; //something obiviously went wrong and you can check the $output and $return_status in your implementations to return more to controller.


Remember this helper file is to work around localhost only. For live server, use the exec () without any sudo
 exec('phantomjs '.realpath('assets/js').'/rasterize.js '.$url.' '.realpath('assets/pdfs').$output,$output_status, $return_status);

Don't forget to double check the files location such as rasterize.js, pdfs folder etc.

Tutorial to add PATH in terminal can be found @http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/

Source: Generating PDFs and Thumbnails of Views.

How to Get Full URL With Query Strings in Codeigniter?

If you use current_url(), it will return the full URL (including segments) of the page being currently viewed.But if your URL contains query string or parameters, it won't include those query strings in the full URL.
For example, if your URL was this:
The function would return:
http://example.com/blog //The url without the query strings.
You can modify the Codeigniter's core URL helper or extend the URL helper to your needs. I prefer to add new function for this keeping the native function as it is.
Create a MY_url_helper.php inside 'application/helpers' folder.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

function current_full_url()
    $CI =& get_instance();

    $url = $CI->config->site_url($CI->uri->uri_string());
    return $_SERVER['QUERY_STRING'] ? $url.'?'.$_SERVER['QUERY_STRING'] : $url;

/* End of file MY_url_helper.php */
/* Location: ./application/helpers/MY_url_helper.php */
Now you can use current_full_url() to view Full URL with query strings. The function would return:

Friday, October 4, 2013

What does PHP exec() return value of 5 mean?

I have been trying to know if the exec() command in php executes successfully or not so that I can print certain messages accordingly.
In the command
exec($command, $return_array, $return_value)
If you execute above command via PHP and get $return_array as empty and $return_value as 5, then that means something is wrong. If the command successfully executes, it should return a value of 0.
5 means Access denied.

Similarly, Here are list of some common return codes and what they means

0 The operation completed successfully. 
1 Incorrect function. 
2 The system cannot find the file specified. 
3 The system cannot find the path specified. 
4 The system cannot open the file. 
5 Access is denied. 
6 The handle is invalid. 
7 The storage control blocks were destroyed. 
8 Not enough storage is available to process this command. 
9 The storage control block address is invalid. 
10 The environment is incorrect. 

The complete list can be found @ Hikesoftware

Tuesday, October 1, 2013

Valid URL Format Checking in CodeIgniter 2.x Using custom/extended Form Valdiation Library

CodeIgniter lacks with URL validation. The only one that it provides is called prep_url which does nothing more then prepend "http://" to URLs if missing.

Create a file in the application/library directory called MY_Form_validation.php. Make the class name MY_Form_validation as well. Be sure that it extends CI_Form_validation, and that it calls the parent constructor. This will allow you to extend the built-in validation library and add additional validators to it.
Then in your code, you can simply add additional validators like:
$rules['URL']  = 'required|prep_url|valid_url_format|url_exists';

The two new validators are valid_url_format which checks for a properly formatted URL and url_exists which checks for a valid server. You should prefix the two with prep_url so that if they don’t enter a scheme the other validators won’t fail.
if (!defined('BASEPATH')) exit('No direct script access allowed');
 * Additional validations for URL format.
 * @package      Module Creator
 * @subpackage  ThirdParty
 * @category    Libraries
 * @author  Anup Shakya 
 * @created 01/10/2013
class MY_Form_validation extends CI_Form_validation{
   public function __construct()
     * Validate URL format
     * @access  public
     * @param   string
     * @return  string
    function valid_url_format($str){
        $pattern = "|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i";
        if (!preg_match($pattern, $str)){
            $this->set_message('valid_url_format', 'The URL you entered is not correctly formatted.');
            return FALSE;
        return TRUE;
    // --------------------------------------------------------------------
     * Validates that a URL is accessible. Also takes ports into consideration. 
     * Note: If you see "php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known" 
     *          then you are having DNS resolution issues and need to fix Apache
     * @access  public
     * @param   string
     * @return  string
    function url_exists($url){                                   
        $url_data = parse_url($url); // scheme, host, port, path, query
        if(!fsockopen($url_data['host'], isset($url_data['port']) ? $url_data['port'] : 80)){
            $this->set_message('url_exists', 'The URL you entered is not accessible.');
            return FALSE;
        return TRUE;
// END Form Validation Class

/* End of file My_Form_validation.php */
/* Location: ./application/libraries/My_Form_validation.php */
In this way, you can extend the Form_validation library without touching core library. Ref: http://brianistech.wordpress.com/2010/11/19/url-validation-in-codeigniter/

How To Remove Last Comma From The End of String in PHP?

If you want to remove the comma from the end of a string, you can use various tricks. But one simple trick is to use PHP inbuilt function rtrim(). The rtrim function (and corresponding ltrim() for left trim) is very useful as you can specify a range of characters to remove.

rtrim() strips whitespace (or other characters) from the end of a string.

$string = "Hello, I, am, Anup,";
echo $string = rtrim($string, ','); //it will remove a char if the last char is a comma

//output : "Hello, I, Am, Anup";
If you want to remove exactly one comma, which may or may not be there, use:
if (substr($string, -1, 1) == ',')
  $string = substr($string, 0, -1);