How to create custom 404 page with Codeigniter

It is always nice to have a good Page-not-found page to keep a good impression on your website even when the link is broken. Here is how I have implemented it on www.LankaMatters.com in 3 steps.

  1. First open routes.php in application/config and set a custom controller name.
  2. $route['404_override'] = 'my404'; //Here my404 is my controller class name.
  3. Create a new controller and write the following code in it. The code is very easy to understand. So I am not going to explain it here.
  4. my404.php   
    <?php
    class my404 extends CI_Controller
    {
        public function __construct()
        {
                parent::__construct();
        }

        public function index()
        {
            $this->output->set_status_header('404');
            $data['content'] = 'error_404'; // View name
            $this->load->view('index',$data);//loading in my template
        }
    }
    ?>
  5. Create a view with your custom message.

That is all. :)

How to post on user’s wall on Facebook?

You can download the source code here Facebook connect for Codeigniter to experiment immediately.

Hope you have aldreay went through my tutorial on Codeigniter library for Facebook. If not please go through it first.

Once user is authenticated with the required access tokens, you can call any methods mentioned in the Graph API at http://developers.facebook.com/docs/reference/api/. Now I will explain how to call the Graph api method to post to the user wall.

Simply write the following function inside the Facebook connect library you have already created. After that you can simply call the function with the wanted details. If user is not loggedcin or no access to post then the function will return false.

function post_to_wall($message,$link="",$photourl="")
{
	if($this->fbSession)
	{
		$param = array('message'=>$message,'cb' => '');           
		if($photourl!="")
		{
			$param["picture"] = $photourl;
		}
		if($link!="")
			$param["link"] = $link;               
		$posts = $this->fb->api('/me/feed','post',$param);
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

 

Same way if you want to get user’s wall posts pass “me/home” to the fb->api method in the above functions.

Hope you learned something. For complete reference of the available functions refer the Facebook Graph API.

Removing index.php from website url – Codeigniter

If you are using Codeigniter sometimes you may feel bore with the index.php in the url. By removing it from the url you can make your website more structured and it will help you in SEO matrices.

  1. Enable the apache ModRewrite module. If you are using wamp server you do it by using the menu in the task bar icon.
  2. Open config.php from system/application/config directory and replace $config['index_page'] = “index.php” b$config['index_page'] =”
  3. Now create the .htaccess file in your web root and add the following lines in it.
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

4. Please if you have installed your Codeigniter in some folder in root the you have to set the base folder to that. For doing it copy paste the following after the first line in step 3. Replace test with the actual folder name.

RewriteBase /test/

A smart Codeigniter model for all functions

Today tip is about extending the Codeigniter Model core class by adding some smart functions to it. After extending it, you no longer required to write any code in your model, except extending your model from our extended Model class and everything will be handled by extended class.
Before continuing with this, I assume you have some experience working with Codeigniter framework and know the folder strucure in it. As the first step, create a file in application/core folder and name it as “MY_model.php”.
Define our new model class in it extending Codeigniter core Model class. The coding will be like the following in first stage.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Model extends CI_Model
{
	public $table;
	public function __construct()
	{
		parent::__construct();
		$this->table = get_Class($this);
		$this->load->database();
	}
}

In the above part we have added a constructor and a variable named $table. We are initializing the $table variable with the class name. We will use the class name as the table name in our methods, when table name is not passed to the mthods.

We are going to have 4 methods insert, update, search and save. Method names self explains the functionality. Method save will update the record when a record already exists with same parimary and inserts if no such record exists.

 

public function save($data,$tablename="")
{
	if($tablename=="")
	{
		$tablename = $this->table;
	}
	$op = 'update';
	$keyExists = FALSE;
	$fields = $this->db->field_data($tablename);
	foreach ($fields as $field)
	{
		if($field->primary_key==1)
		{
			$keyExists = TRUE;
			if(isset($data[$field->name]))
			{
				$this->db->where($field->name, $data[$field->name]);
			}
			else
			{
				$op = 'insert';
			}
		}
	}
 
	if($keyExists && $op=='update')
	{
		$this->db->set($data);
		$this->db->update($tablename);
		if($this->db->affected_rows()==1)
		{
			return $this->db->affected_rows();
		}
	}
 
	$this->db->insert($tablename,$data);
 
	return $this->db->affected_rows();
 
}
 
function search($conditions=NULL,$tablename="",$limit=500,$offset=0)
{
	if($tablename=="")
	{
		$tablename = $this->table;
	}
	if($conditions != NULL)
		$this->db->where($conditions);
 
	$query = $this->db->get($tablename,$limit,$offset=0);
	return $query->result();
}
 
function insert($data,$tablename="")
{
	if($tablename=="")
		$tablename = $this->table;
	$this->db->insert($tablename,$data);
	return $this->db->affected_rows();
}
 
function update($data,$conditions,$tablename="")
{
	if($tablename=="")
		$tablename = $this->table;
	$this->db->where($conditions);
	$this->db->update($tablename,$data);
	return $this->db->affected_rows();
}
 
function delete($conditions,$tablename="")
{
	if($tablename=="")
		$tablename = $this->table;
	$this->db->where($conditions);
	$this->db->delete($tablename);
	return $this->db->affected_rows();
}

 

After adding above 4 methods, using our Model class is easy. Just create a model by inheriting the new model class. Below is an example class and described the usage below the coding.

 

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Samlpe extends MY_Model
{
	public function __construct()
	{
		parent::__construct();
	}
}

 

We have defined the Model class without any methods in it, and see below how we can use it in a controller.

$this->load->model(“Sample”);

$condition['id'] = ’1′;

$this->sample->delete($condition); //Delete from Sample table, if same as class name then no need to pass table name

$this->sample->delete($condition,”AnotherTable”); //If delete from some other table

$data['fieldName'] = ‘field value’;

$data['fieldName2'] = ‘field value 2′

$this->sample->save($data);

I think this helped you in speeder development of Codeigniter PHP coding, next time will come up with some other tricks.

 

How to use Facebook PHP SDK v.3.0.0 with Codeigniter?

There is some changes has been done in the Facebook PHP SDK v.3.0.0. There is no more method named as getSession. So if you have updated to the new Fecebook PHP SDK then you might have to modify your Codeigniter Facebook connect library.

You can follow these simple steps to have a working Codeigniter Facebook library.

  1. Create a Config file in application/facebook.php with the following code in it.
  2. $config['appId'] = 'Your Facebook App ID';
    $config['secret'] = 'Your secret Code';
  3. There is two files provided starting from V.3.0.0 of Facebook PHP SDK. Create a folder in application library and name it as facebook.
  4. Download the Facebook PHP SDK files and place it in the folder application/library/facebook. You can download it from https://github.com/facebook/php-sdk
  5. Create a new file and name it as fb_connect.php in application/library and copy the following code inside that folder. 
    <?php
    	include(APPPATH.'libraries/facebook/facebook.php');
     
    	class Fb_connect extends Facebook{
     
    		//declare public variables
    		public 	$user 			= NULL;
    		public 	$user_id 		= FALSE;
     
    		public $fb 			= FALSE;
    		public $fbSession	= FALSE;
    		public $appkey		= 0;
     
    		//constructor method.
    		public function __construct()
    		{
                        $CI = & get_instance();
                        $CI->config->load("facebook",TRUE);
                        $config = $CI->config->item('facebook');
                        parent::__construct($config);
                        $this->user_id = $this->getUser(); // New code
     
                        $me = null;
                        if ($this->user_id) {
                            try {
                                $me = $this->api('/me');
                                $this->user = $me;
                                } catch (FacebookApiException $e) {
                                    error_log($e);
                                }
    			}
    		} 
     
    	} // end class

Now create a Controller and name it as user, and write the following methods in it.

  
function loginByFacebook(){
        	$this->load->library('fb_connect');
	        $param['redirect_uri']=site_url("user/facebook");
	        redirect($this->fb_connect->getLoginUrl($param));
	}
 
	function facebook() {
	        $this->load->library('fb_connect');
	        if (!$this->fb_connect->user_id) {
	            //Handle not logged in,
	        } else {
	           $fb_uid = $this->fb_connect->user_id;
	           $fb_usr = $this->fb_connect->user;
	           //Hanlde user logged in, you can update your session with the available data
        	   //print_r($fb_usr) will help to see what is returned
	        }
	}

 

 

That is all about the coding now when ever you need to login with facebook just redirect to user/loginByFacebook and your login will handled automatically by Facebook. But you need to update the facebook() method with the actions success and failure conditions.

Repopulate form fields in Codeigniter

 

I had some problems in repopulating the form POST values on the fields which are not used in the CI form validation. This is how I have solved it.

When we use the set_value, if the form validation library is loaded then it looks for the value in the form validation library object. So if you are not going to use any validation on the field, you can only load the form helper so that set_value work even if the field is not used in the validation.

But let say if you are doing validation on some fields then the above approach will not work. In that case you can set a dummy validation on the field as following.

$this->form_validation->set_rules(“field_name”,”Display Name”,”");

If you are not happy with the above indirect way, then you can overwrite the set_value function from the form helper class by following the steps below.

1) Create a file named MY_form_helper.php in helper folder. (application/helper)

2) Write down the following code in it.

 

  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2.  
  3. /**
  4. * Form Value
  5. *
  6. * Grabs a value from the POST array for the specified field so you can
  7. * re-populate an input field or textarea.  If Form Validation
  8. * is active it retrieves the info from the validation class
  9. *
  10. * @access   public
  11. * @param   string
  12. * @return   mixed
  13. */
  14. if ( ! function_exists('set_value'))
  15. {
  16.   function set_value($field = '', $default = '')
  17.   {
  18.       $OBJ =& _get_validation_object();
  19.  
  20.       if ($OBJ === TRUE && isset($OBJ->_field_data[$field]))
  21.       {
  22.         return form_prep($OBJ->set_value($field, $default));
  23.       }
  24.       else
  25.       {
  26.         if ( ! isset($_POST[$field]))
  27.         {
  28.           return $default;
  29.         }
  30.  
  31.         return form_prep($_POST[$field]);
  32.       }
  33.   }
  34. }
  35.  
  36. /* End of file MY_form_helper.php */
  37. /* Location: ./application/helpers/MY_form_helper.php */

 

But in the last approach, you will have to rewrite all the helper functions based on the need basis. So it is better to go for the second one in case you need a validation on some fields otherwise go for the first approach.