Creating and checking user session using CodeIgniter library

In this article, we are going to discuss about How to create and check the User session using CodeIgniter library. If we create a web application with login (sign in) functionality, then the system must use session to check whether the user is logged in or not. Session is the most common way to checking it. In Codeigniter, using Session Class you can use simple function inside controller, it's something like this:

class User extends Controller {
// constructor class
    function __construct()
    {
        parent::Controller();
        $this->load->library('session');
    }
    function index()
    {
        $this->load->view('user/index');
    }
    function login()
    {
        // if user already logged in, redirect to user index
        if ($this->_is_logged_in())
        {
            redirect('user/index');
        }
       else
        {
            $this->load->view('user/login');
        }
    }
    function register()
    {
        // if user already logged in, redirect to user index
        if ($this->_is_logged_in())
        {
            redirect('user/index');
        }
        else
        {
            $this->load->view('user/register');
        }
    }
    // checking user logged user by registered session
    function _is_logged_in()
    {
        $logged = $this->session->userdata('user_id');
        if ($logged)
       {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
}

The problem using that method is when we have multiple controller using the same function, we have to write the same code again and again. So this article have simple answer. Another solution is creating that user session checking function in model class, but when we create a class model in CodeIgniter we must extends CI Model Class and I don't think we need to extends the CI Model Class, so I create my own user session library, and here it goes:

Create a php file named MY_Usession.php in folder application/libraries/, Insert this code and save it:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Usession extends CI_Session {
    public $logged_in = FALSE;
    public function  __construct() {
        parent::CI_Session();
        $this->is_logged_in();
    }
    public function is_logged_in()
    {
        $logged = $this->userdata('user_id');
        $this->logged_in = ($logged) ? TRUE : FALSE;
    }
}
?>

Open file application/config/autoload.php add the library to the $autoload["libraries"] variable, it may something like this

$autoload['libraries'] = array('database', 'session', 'my_usession');

Yup now all set, when we load every controller, the MY_Usession library will check whether the user is logged in or not, and you can access it in Controller or in a View by calling it's property

$this->my_usession->logged_in

For example using in Controller:

class User extends Controller {
// constructor class
function __construct()
{
parent::Controller();
$this->load->library('session');
}
function index()
{
$this->load->view('user/index');
}
function login()
{
// if user already logged in, redirect to user index
if ($this->my_usession->logged_in)
{
redirect('user/index');
}
else
{
$this->load->view('user/login');
}
}
function register()
{
// if user already logged in, redirect to user index
if ($this->my_usession->logged_in)
{
redirect('user/index');
}
else
{
$this->load->view('user/register');
}
}
}

Steps to check the request type in Cakephp

In this article, we are going to discuss about How to check the request type in Cakephp. In Cakephp, we have many number of request objects. The default request object in Cakephp is "CakeRequest". By default CakeRequest is assigned to $this->request, and is available in Controller, Views and Helpers. By getting the request type, we can do the operations accordingly.

CakeRequest provide many interfaces to access the request parameters.

  1. The first is as object properties, 
  2. Second is array indexes, 
  3. Third is through $this->request->params:


// Passed arguments
$this->request->pass;
$this->request['pass'];
$this->request->params['pass'];

// named parameters
$this->request->named;
$this->request['named'];
$this->request->params['named'];

Change the ErrorController to work with AJAX in Zend Framework

In this article, we are going to discuss about How to change the ErrorController to work with AJAX in Zend Framework. Zend Framework is mostly used for web application. By deafult, in Zend Framework we have a set of default ErrorControllers. If we create a web application using Zend app which makes AJAX calls , it will notify that if an error occurs, we'll get a chunk of JSON followed by the HTML for the error page. This is fine if our users hit the page in the browser but it can cause problems with our JavaScript being able to correctly decode your JSON.

By changing the ErrorController, we can easily get the JSON by using the AJAX call.

Open the file "/application/controllers/ErrorController.php". In this we need to register the errorAction in an AJAX context. It will tell the Zend Framework that if it detects an XML HTTP Request and there's a parameter called "format" with a value of "json" that it should automatically turn off the view and the layout. This will leave us with just the JSON part of the response.

If you don't have an init method in your ErrorController class, create one like this:

/** 
 * Initializes the error action to deal with AJAX responses
 * 
 * @return null
 */
public function init()
{
    $this->_helper->ajaxContext->addActionContext(
        'error', array('json')    
    )->initContext();
}

The above code does most of the work, but chances are you may want to add a few more useful pieces of information to your JSON response. Typically in any AJAX calls we'll have a success variable that indicates whether the call we made worked or not.

Add this line to the top of the errorAction method:

$this->view->success = false;

To test the above code, you can have your action your AJAX call hits throw an exception that you don't catch. This is as simple as:

throw new Exception('Foo');

If we do this, and view the JSON in chrome or Firebug, you'll see a success = false, an empty exception object, an empty request object and a very helpful message with a value of "Application error".

The empty request and exception object are because those are PHP objects that are getting set into the view within the ErrorController. In a JSON response, it may be helpful to add some more information from within those objects.

Near the end of the errorAction method, we should see some code like:

// conditionally display exceptions        
if ($this->getInvokeArg('displayExceptions') == true) {
    $this->view->exception = $errors->exception;        
}

If you want this additional information to only be sent to the view if displayExceptions is turned on and if it's an AJAX call, you can make the following modifications.

// conditionally display exceptions        
if ($this->getInvokeArg('displayExceptions') == true) {            
    if ($this->_request->isXmlHttpRequest()) {                
        $this->view->exception  = $errors->exception
            ->getMessage();                
        $this->view->stackTrace = $errors->exception
            ->getTrace();             
    } else {                
        $this->view->exception = $errors->exception;        
    }        
}

This code will replace that empty exception object with the message from the exception. It will also create a new stackTrace object in the JSON which is an array of objects containing information about the stack trace.  It's completely up to you if you want to include that information or not.

The other empty object showing up in the JSON is the empty request. If knowing more about the request would be useful, change this

$this->view->request = $errors->request;

to this:

if ($this->_request->isXmlHttpRequest()) {
    $this->view->request = $this->_request->getParams();
} else {
    $this->view->request = $errors->request;
}

This chunk of code will replace that empty request object with an array of key: value pairs for all of the parameters in the request.

That's all there is to it. Your AJAX calls will now get a JSON response even if an error happens in one of your controllers.

I hope this helps and I look forward to hearing from you.

Steps to create File Upload Component Cakephp

In this article, we are going to discuss about How to create a file upload component in Cakephp. File upload is a most used component in each and every application. Here we are going to create our own file upload component in Cakephp.

To create a file upload in a form, we need to change the following in our .ctp file.

Step 1 : Create a form

Create a form in Cakephp by using the below code.

echo $this->Form->create('Company',array('type'=>'file'));

Step 2 : Create a file upload field

Use the below code to create file upload field in the form.

echo $this->Form->input('company_logo',array('type'=>'file'));

Changes in the .ctp file is completed. Now open the controller file and add the Resizer component.

App::import('Component', 'Resizer');

Step 3 : Initialize the resizer component

Open the Resizer component file and the below code to initialize the resizer component.

$this->Thumbcontent  = new ImageComponent();

Step 4 : Call the resizer function

After initialize the resizer component, call the resizer function, which at a time upload the file to the given folder location and resize the image also.

$this->Thumbcontent->resize($this->data['Company']['company_logo']['tmp_name'], WWW_ROOT.'img'.DS.'company'.DS.$time.'_'.$this->data['Company']['company_logo']['name'],550,550,false,70);


Here,

  1. First argument is the file tmp_name which you want to upload, 
  2. Second argument is the location where you want to keep the file, 
  3. Third and forth are the upload image resize with and height, 
  4. Sixth is the water mark true or false and 
  5. Seventh is image quality.

Create POP3 filter in PHP using Zend Framework

In this article, we are going to discuss about how to create POP3 filter in PHP using Zend Framework. POP3 is nothing but Post Office Protocol (POP) is an application-layer Internet standard protocol used by local e-mail clients to retrieve e-mail from a remote server over a TCP/IP connection. It is mostly used to send and receive an Email in an application. I'm going to explain about how to create POP3 filter in php using Zend framework.

Create a file in the server named "pop3filter.php" and add the below codes in that file.

<?php
require_once 'Zend/Mail/Storage/Pop3.php';

$spammers = array(
    "email1@example.com",
    "email2@example.com",
);

$mail = new Zend_Mail_Storage_Pop3(array('host' => 'pop3.example.com', 'user' => 'john.doe@example.com', 'password' => 'example', 'port' => 110));

echo $mail->countMessages() . " messages found\n";

foreach ($mail as $messageId => $message) {
  echo "{$messageId} : Mail from '{$message->from}': {$message->subject}\n";

  if(in_array(strtolower($message->from), $spammers, true)) {
    $mail->removeMessage($messageId);
    echo "Message removed\n";
  }
}

?>

Crontab

$ crontab -e
# m h  dom mon dow   command
*/10 * * * * /usr/bin/php /home/john/bin/pop3filter/pop3filter.php > /dev/null 2>&1

Crop Image to Square dimension in CodeIgniter

CodeIgniter have a powerful image manipulation class. In this article we are going to discuss about How to use this class and Crop image to a square dimension in CodeIgniter (CI). Here we are going to discuss How to generate the square shape thumbnail from the uploaded image in CodeIgniter (CI).

It will crop the image in the server not by URL. If you have a dynamic variable to locate an image on the server, you can create function to check the image format (png, jpg, gif...etc..) and then use PHP GD function (imagecreatefromjpeg or imagecreatefrompng or imagecreatefromgif) to get the image width and height, in this code below it assume the image only in .jpg format.

If you want to crop image from the uploaded file by the user it will make it easier, cause when you use CodeIgniter file uploading class there's a built in property to get uploaded image width and image height automatically after the image was uploaded.

Use the below code to crop the image in CodeIgniter (CI)

public function crop()
{
    $img_path = 'uploads\capsamples.jpg';
    $img_thumb = 'uploads\capsamples_thumb.jpg';

    $config['image_library'] = 'gd2';
    $config['source_image'] = $img_path;
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = FALSE;

    $img = imagecreatefromjpeg($img_path);
    $_width = imagesx($img);
    $_height = imagesy($img);

    $img_type = '';
    $thumb_size = 100;

    if ($_width > $_height)
    {
        // wide image
        $config['width'] = intval(($_width / $_height) * $thumb_size);
        if ($config['width'] % 2 != 0)
        {
            $config['width']++;
        }
        $config['height'] = $thumb_size;
        $img_type = 'wide';
    }
    else if ($_width < $_height)
    {
        // landscape image
        $config['width'] = $thumb_size;
        $config['height'] = intval(($_height / $_width) * $thumb_size);
        if ($config['height'] % 2 != 0)
        {
            $config['height']++;
        }
        $img_type = 'landscape';
    }
    else
    {
        // square image
        $config['width'] = $thumb_size;
        $config['height'] = $thumb_size;
        $img_type = 'square';
    }

    $this->load->library('image_lib');
    $this->image_lib->initialize($config);
    $this->image_lib->resize();

    // reconfigure the image lib for cropping
    $conf_new = array(
        'image_library' => 'gd2',
        'source_image' => $img_thumb,
        'create_thumb' => FALSE,
        'maintain_ratio' => FALSE,
        'width' => $thumb_size,
        'height' => $thumb_size
    );

    if ($img_type == 'wide')
    {
        $conf_new['x_axis'] = ($config['width'] - $thumb_size) / 2 ;
        $conf_new['y_axis'] = 0;
    }
    else if($img_type == 'landscape')
    {
        $conf_new['x_axis'] = 0;
        $conf_new['y_axis'] = ($config['height'] - $thumb_size) / 2;
    }
    else
    {
        $conf_new['x_axis'] = 0;
        $conf_new['y_axis'] = 0;
    }

    $this->image_lib->initialize($conf_new);

    $this->image_lib->crop();
}