Monday, April 29, 2013

Why UTF-8 doesn’t work to display European characters in the Codeigniter or PHP

Writing an application is easy. Writing an application that supports all characters from multiple languages? Not so easy.


The main problem comes from way back, when the main language in computing was English. The ASCII characters were given numbers from 1 to 128 a-z, A-Z, 0-9 and punctuation. That is fine for the English language but pretty much every other language out there has characters that don't fit in there. To address this, we have UTF-8, which can store extra characters as multiple-bits and is backwards compatible with ASCII.

To make your CodeIgniter application play nicely with UTF-8 you have a few things to think about.

CodeIgniter by default is set to use UTF-8 for much of its internal functionality, so just make sure the charset is set to UTF-8 in your application/config/config.php file.

$config['charset'] = "UTF-8";


Setting UTF-8 as meta tag in the header is not sufficient, if you are working European characters. For example, to display Swedish characters å,ä,ö in the website. 


<meta http-equiv="content-type" content="text/html; charset="utf-8">

You will get following rendered text in your browser.
Hej! Det h�r meddelandet �r p� Svenska.(default)

You have to save file as UTF-8 as well. But using the correct doctype and encoding for the document helps crippled browsers.

If you are using coda as text editor, Check at Text/Encoding to know which encoding are you using while saving the file.

If you save the file with correct encoding i.e Unicode UTF-8 , then you will get the correct result:

Hej. Det här meddelandet är på Svenska.

Hope this will help who is having problem.

Ref: http://philsturgeon.co.uk/blog/2009/08/utf-8-support-for-codeigniter and  http://ellislab.com/forums/viewthread/128608/

Tuesday, April 23, 2013

Value Checking in PHP with isset() and empty()

PHP has several functions which can be used to determine certain things about the value of a variable. None of these functions are particularly complex, but they can be difficult to tell apart – for instance, when to use empty()versus isset().
The PHP Doc site has a Type Comparison Table demonstrating the result you get from these comparison functions based on several different values. This table serves as a great reference to find out which function is designed to provide the kind of comparison you need.
For this post, I want to focus on three specific ways of checking values. Considering the following:
$nullvar;
$setvar = "we are set.";
$setbutfalse = false;

What happens when you run isset(), empty(), or if() on each of these variables? Here are some pointers:
isset()
  • isset() returns true if a variable is set, no matter what its contents. The contents may be: false, 0, ”, or anything else, and isset() will still return true. So long as the variable has had some value set, it will be true. There is one exception.
  • isset() returns false if a variable has never been set or if a variable has been assigned the specific keyword NULL (i.e., $var = NULL;).
  • For the above variables, isset($nullvar) will be false; isset($setvar) will be true; isset($setbutfalse) will be true.
empty()
  • empty() returns true for any variable that is not set, contains no value, or contains a value that equals zero (such as 0, “0″, false, etc).
  • For the above variables, empty($nullvar) will be true; empty($setvar) will be false; empty($setbutfalse) will be true.
if()
  • if($var) does essentially the opposite of empty($var). When checking a variable with if($var), it will return true if the variable is set and contains some value other than zero/false.
  • For the above variables, if ($nullvar) will be false; if ($setvar) will be true; if ($setbutfalse) will be false.
When to use which? It depends on what you are trying to do.
  • If you want to see if a variable is set, period, and don’t care what its value is, use isset().
  • If you want to see if a variable is empty or contains a value that equals 0 or false, use empty().
  • If you want to see if a variable is not empty and does not contain a false/zero value, use !empty(). For example, if (!empty($passed)).
  • For the above example, you could also use if ($passed) and it would do the same thing.
Perhaps this post helps clear a little of the fog. Perhaps it just makes the fog thicker. Either way, it shows that PHP has a lot of little tools to meet a lot of use cases. In PHP, there are many ways to skin a cat. The trick is knowing which way is best.
Ref: http://croberts.me/2011/12/26/value-checking-in-php-with-isset-and-empty/ 

Friday, April 19, 2013

How to manage Codeigniter Session Timeout?


Codeigniter session timeout value is specified in the config.php file inside the config directory. You can change the default value of 7200 seconds to any value you want using the sess_expiration variable. Session timeout can be avoided by setting the value to 0.
// Session will expire in 10 seconds
$config['sess_expiration']= 10;

// Session will not expire $config['sess_expiration']= 0;

Tuesday, April 16, 2013

A bootstrap for the CodeIgniter PHP Framework

The Template library written for the CodeIgniter PHP-framework using popular bootstrap.



Check out @https://github.com/aliasproject/CodeIgniter-Bootstrap

Template Library for CodeIgniter, the PHP Framework

The Template library, written for the CodeIgniter PHP-framework, is a wrapper for CodeIgniter's View implementation. Template is a reaction to the numerous questions from the CI community regarding how one would display multiple views for one controller, and how to embed “views within views” in a standardized fashion. In addition, Template provides extra Views loading capabilities, the ability to utilize any template parser (like Smarty), and shortcuts for including CSS, JavaScript, and other common elements in your final rendered HTML.

Read more on http://www.williamsconcepts.com/ci/codeigniter/libraries/template/

I am going to try to implement this library in my next project. Hope it will save my time. 

Friday, April 12, 2013

CodeIgniter Caching Problem with HTTP Headers (Content-Type)


Problem Description

I use 

$this->output->cache(n); 
to cache the file for at least n minutes. This works perfect for the first request the users’ browser makes. The second time, the  files seem to have the Content-type text/html, so no custom header type is applied at all!

How can I use caching and make sure the Content-Type header is also cached, so codeigniter does not fall back to text/html

Solution:


When you set a header via $this->output->set_header(), but also use caching via $this->output->cache(), those headers you sent will not be cached along with your content.
This can be very problematic: if you're caching CSS, for example, you want the cache to return that CSS along with the Content-Type header "text/css" - otherwise most browsers will interpret your CSS as just plain text, and hence not use it for rendering. With this simple extension to the Output class, headers will also be cached and returned.

Advantages over built-in cache

This extension is more memory efficient as the current (1.7.0) caching system, so even if you don't need the header caching, this extension is worth installing. 

Instructions

Create a file in application/libraries named MY_Output.php ( as described in the user guide ) and copy/paste the following code:
   <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * MY_Output
 * 
 * Modified _write_cache and _display_cache to allow for header caching
 * works with CodeIgniter 1.7.0
 *
 * @package        CodeIgniter
 * @subpackage    Libraries
 * @category    Output
 * @author        Arjen van Bochoven
 * @link        http://codeigniter.com/wiki/Cache_headers
 */

class MY_Output extends CI_Output {


    // --------------------------------------------------------------------

    /**
     * Write a Cache File
     *
     * @access    public
     * @return    void
     */    
    function _write_cache($output)
    {
        $CI =& get_instance();    
        $path = $CI->config->item('cache_path');

        $cache_path = ($path == '') ? BASEPATH.'cache/' : $path;
    
        if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
        {
            return;
        }
    
        $uri =    $CI->config->item('base_url').
                $CI->config->item('index_page').
                $CI->uri->uri_string();
    
        $cache_path .= md5($uri);

        if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
        {
            log_message('error', "Unable to write cache file: ".$cache_path);
            return;
        }
    
        $expire = time() + ($this->cache_expiration * 60);
            
        if (flock($fp, LOCK_EX))
        {
            fwrite($fp, serialize(array('exp' => $expire, 'headers' => $this->headers, 'output' => $output)));
            flock($fp, LOCK_UN);
        }
        else
        {
            log_message('error', "Unable to secure a file lock for file at: ".$cache_path);
            return;
        }
        fclose($fp);
        @chmod($cache_path, DIR_WRITE_MODE);

        log_message('debug', "Cache file written: ".$cache_path);
    }

    // --------------------------------------------------------------------

    /**
     * Update/serve a cached file
     *
     * @access    public
     * @return    void
     */    
    function _display_cache(&$CFG, &$URI)
    {
        $cache_path = ($CFG->item('cache_path') == '') ? BASEPATH.'cache/' : $CFG->item('cache_path');
        
        if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
        {
            return FALSE;
        }
    
        // Build the file path.  The file name is an MD5 hash of the full URI
        $uri =    $CFG->item('base_url').
                $CFG->item('index_page').
                $URI->uri_string;
            
        $filepath = $cache_path.md5($uri);
    
        if ( ! @file_exists($filepath))
        {
            return FALSE;
        }

        if ( ! $fp = @fopen($filepath, FOPEN_READ))
        {
            return FALSE;
        }
        
        flock($fp, LOCK_SH);
        
        $cache = '';
        if (filesize($filepath) > 0)
        {
            $cache = fread($fp, filesize($filepath));
        }
    
        flock($fp, LOCK_UN);
        fclose($fp);
        
        // Restore the cache array
        $cache = unserialize($cache);
        
        // Validate cache file
        if ( ! isset($cache['exp'] ) OR ! isset($cache['headers']) OR ! isset($cache['output']))
        {
            return FALSE;
        }
        
        // Has the file expired? If so we'll delete it.
        if (time() >= trim($cache['exp']))
        {         
            @unlink($filepath);
            log_message('debug', "Cache file has expired. File deleted");
            return FALSE;
        }
        
        // Restore headers
        $this->headers = $cache['headers'];
                
        // Display the cache
        $this->_display($cache['output']);
        log_message('debug', "Cache file is current. Sending it to browser.");        
        return TRUE;
        
    }
}

Ref: https://github.com/EllisLab/CodeIgniter/wiki/Cache-headers

Flushing CodeIgniter's cache or Deleting Caches in Codeigniter

Enabling and deleting caches in Codeigniter is fairly straightforward and easy. In this post, I am writing about deleting caches. You no longer need to delete caches manually in Codeigniter 2.x version.



If you no longer wish to cache a file in Codeigniter you can remove the cache files. Following are two methods to do it.

Clearing all cache

You can clear the entire cache directory by calling $this->output->clear_all_cache();

Note: This will not remove the .htaccess and index.html files in the applications/cache folder.

//Clears all cache from the cache directory

$this->output->clear_all_cache();

This method returns NULL.

Clearing a cached path

You can clear any specified path of its cache by calling following method.

//Clears the cache for the specified path

$this->output->clear_path_cache($uri);

 This method will return boolean TRUE if successful, FALSE if not.


You can find all the information/source-code about clearing cache inside "application/core/MY_Output.php"

Thursday, April 11, 2013

Codeigniter page caching with query string

Fig: Basic Page Cache Flow


CodeIgniter lets you cache your pages in order to achieve maximum performance. When a page is loaded for the first time, the cache file will be written to your application/cache folder.
To enable caching, put the following tag in any of your controller functions:

$this->output->cache(n);

Where n is the number of minutes you wish the page to remain cached between refreshes.

Warning: Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for your controller with a view.

Problem:

It work only with segment based url. 

What I'm seeing in my use cases and in the Output class code is that the caching is solely segment based. As such, http://www.example.com/segment/?q=foo andhttp://www.example.com/segment/?q=bar are treated as identical requests.

If you want your caching to  work for query string as well,
You can just copy that code below and put it in application/core/MY_Output.php .



<?php



/**

 * @author vee

 * @copyright http://www.okvee.net

 */



class MY_Output extends CI_Output {

     

     

    function __construct() {

        parent::__construct();

    }// __construct

     

     

    /**

     * Update/serve a cached file

     *

     * @access    public

     * @return    void

     */

    function _display_cache(&$CFG, &$URI)

    {

        $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');



        // Build the file path.  The file name is an MD5 hash of the full URI

        $uri =    $CFG->item('base_url').

                $CFG->item('index_page').

                $URI->uri_string;

        // buld query strings

        $querystrings = $_SERVER['QUERY_STRING'];

        if ( $querystrings != null ) {$querystrings = "?".$querystrings;}

        $uri = $uri.$querystrings;



        $filepath = $cache_path.md5($uri);



        if ( ! @file_exists($filepath))

        {

            return FALSE;

        }



        if ( ! $fp = @fopen($filepath, FOPEN_READ))

        {

            return FALSE;

        }



        flock($fp, LOCK_SH);



        $cache = '';

        if (filesize($filepath) > 0)

        {

            $cache = fread($fp, filesize($filepath));

        }



        flock($fp, LOCK_UN);

        fclose($fp);



        // Strip out the embedded timestamp

        if ( ! preg_match("/(\d+TS--->)/", $cache, $match))

        {

            return FALSE;

        }



        // Has the file expired? If so we'll delete it.

        if (time() >= trim(str_replace('TS--->', '', $match['1'])))

        {

            if (is_really_writable($cache_path))

            {

                @unlink($filepath);

                log_message('debug', "Cache file has expired. File deleted");

                return FALSE;

            }

        }



        // Display the cache

        $this->_display(str_replace($match['0'], '', $cache));

        log_message('debug', "Cache file is current. Sending it to browser.");

        return TRUE;

    }// _display_cache

     

     

    /**

     * Write a Cache File

     *

     * @access    public

     * @return    void

     */

    function _write_cache($output)

    {

        $CI =& get_instance();

        $path = $CI->config->item('cache_path');



        $cache_path = ($path == '') ? APPPATH.'cache/' : $path;



        if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))

        {

            log_message('error', "Unable to write cache file: ".$cache_path);

            return;

        }



        $uri =    $CI->config->item('base_url').

                $CI->config->item('index_page').

                $CI->uri->uri_string();

        // buld query strings

        $querystrings = $_SERVER['QUERY_STRING'];

        if ( $querystrings != null ) {$querystrings = "?".$querystrings;}

        $uri = $uri.$querystrings;



        $cache_path .= md5($uri);



        if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))

        {

            log_message('error', "Unable to write cache file: ".$cache_path);

            return;

        }



        $expire = time() + ($this->cache_expiration * 60);



        if (flock($fp, LOCK_EX))

        {

            fwrite($fp, $expire.'TS--->'.$output);

            flock($fp, LOCK_UN);

        }

        else

        {

            log_message('error', "Unable to secure a file lock for file at: ".$cache_path);

            return;

        }

        fclose($fp);

        @chmod($cache_path, FILE_WRITE_MODE);



        log_message('debug', "Cache file written: ".$cache_path);

    }// _write_cache

     

     

}
 

Ref: codeigniter cache with querystringWeb Page Caching


Tuesday, April 9, 2013

How to return view’s as data in Codeigniter?

View’s can be returned as data with a third parameter ( setting to TRUE) as follows

   $output = $this->load->view('view', $data, TRUE);

You can use this option for many purposes. I have used it for constructing downloads and to grab and print complete html template. You can used it to build PDFs with the help of some custom libraries or function.