Wednesday, July 04, 2012

CodeIgniter Session


Open the file config.php from the directory root/application/config/ location. Edit the page as following




$config['encryption_key'] = 'Your Encryption Key';


$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  =  300;


Where 
 'sess_cookie_name' =  the name you want for the cookie
 'sess_expiration' =  the number of SECONDS you want the session to last.
   by default sessions last 7200 seconds (two hours).  Set to zero for no expiration.
 'sess_expire_on_close' =  Whether to cause the session to expire automatically
   when the browser window is closed
 'sess_encrypt_cookie' =  Whether to encrypt the cookie
 'sess_use_database' =  Whether to save the session data to a database
 'sess_table_name' =  The name of the session database table
 'sess_match_ip' =  Whether to match the user's IP address when reading the session data
 'sess_match_useragent' = Whether to match the User Agent when reading the session data
 'sess_time_to_update' =  how many seconds between CI refreshing Session Information




As we have set  'session_use_database' value is true and 'sess_table_name' value is 'ci_sessions'. So create a table your database file name as ci_sessions. The table structure is as follows:


CREATE TABLE IF NOT EXISTS  `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);


By default the table is called ci_sessions, but you can name it anything you want as long as you update the application/config/config.php file so that it contains the name you have chosen


Now open the autoload.php file from root/application/config/ location and edit the file as following


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


Now I have created a controller in the root/application/controllers/ directory. The file name is sessionauto.php file and edit the file as follow


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


class Sessionauto extends CI_Controller 
{
public function index()
{
$this -> load -> view('session_auto');
}
}




Now create a file in the view in the root/application/views directory . I have named it seesion_auto.php. Edit the file as follows


<!DOCTYPE html>
<html>
<head>
<title>Auto Set Session View</title>
</head>
<body>
<b>Session ID :</b> <?php echo $this -> session -> userdata('session_id'); ?> <br />
<b>IP Address :</b> <?php echo $this -> session -> userdata('ip_address'); ?> <br />
<b>User Agent :</b> <?php echo $this -> session -> userdata('user_agent'); ?> <br />
<b>Last Activity :</b> <?php echo $this -> session -> userdata('last_activity'); ?> <br />
</body>
</html>


Now if you run the controller then you will get the result something like this


Session ID : 1314d5a77244c256605bbf2bcf9e93f5 
IP Address : 127.0.0.1 
User Agent : Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11 
Last Activity : 1341385732 


If you look into your created table field value then you will get the same value as view. But the session_id value will change every 5mins as we have set the  sess_time_to_update =300. Here 300 is seconds.
$config['sess_time_to_update']  =  300;

Tuesday, July 03, 2012

Browser Detection with Codeigniter

Like most other classes in CodeIgniter, the User Agent class is initialized in your controller using the $this -> load -> library function:
$this -> load -> library('user_agent');
Or 

You can auto-load it by editing the autoload.php file. You can find the file in the application/config/autoload.php file. Just find the $autoload array and add 'user_agent' like below
$autoload['libraries'] = array('user_agent');

Now in the Controller file I have named it useragent.php file edit as follow:

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


class Useragent extends CI_Controller 
{
public function index()
{
$this -> load -> view('user_agent');
}
}


Now in the view file I have named it user_agent.php file edit as follow:
</span><span style="background-color: white; ">User Agent Information</span><span style="background-color: white; ">


<html>
<head>
<title>User Agent Information</title>
<head>


<body>
<?php
        if ($this -> agent -> is_browser()) {
        $agent = $this -> agent -> browser().' '.$this -> agent -> version(); }
        elseif ($this -> agent -> is_robot()) {
        $agent = $this -> agent -> robot(); }
        elseif ($this -> agent -> is_mobile()) {
        $agent = $this -> agent -> mobile(); } 
        else { $agent = 'Unidentified User Agent'; }
        ?>


<?php echo $agent; ?> <br />
<?php echo $this -> agent -> platform(); ?> <br />
<?php echo $this -> agent -> is_referral();?> <br />
<?php echo $this -> agent -> browser();?> <br />
<?php echo $this -> agent -> version();?> <br />
<?php if($this -> agent -> is_referral()) echo $this -> agent -> referrer();?> <br />
<?php echo $this -> agent -> agent_string(); ?> <br />
<?php if($this -> agent -> accept_lang('en')) echo 'English'; ?> <br />
<?php if($this -> agent -> accept_charset('utf-8')) echo 'utf-8'; ?>
</body>




Output: I have executed this code in my localhost it output
Chrome 20.0.1132.47 

Windows 7 



Chrome 

20.0.1132.47 



Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11 

English 

utf-8


Remove index.php Codeigniter

Create a .htaccess file in the root directory of your hosting. Then write the following code to this .htaccess file and save it.


RewriteEngine on
RewriteCond $1 !^(index\.php|system|user_guide|robots\.txt)
RewriteRule ^(.+)$ /codeigniter/index.php?$1 [L]


Now open the file named config.php from /application/config directory

Find the line $config['index_page'] = 'index.php'; 
Turn this line to $config['index_page'] = '';

That's all. Now call your controller with the site name.

Friday, June 29, 2012

Abbreviations Use In Web Languages

  • PHP - Personal Home Page / Hypertext Preprocessor
  • CGI - Common Gateway Interface
  • CLS - Command Line Scripting
  • CLI – Command Line Interface
  • OOP - Object Oriented Programming
  • IIS – Internet Information Services
  • GUI – Graphical User Interface
  • RAD – Rapid Application Development
  • CMS – Content Management System
  • ASCII - American Standard Code for Information Interchange
  • RDBMS – Relation Database Management System
  • XSS – Cross Site Scripting
  • DOS – Denial of Service
  • CIL – Common Intermediate Language
  • PECL – PHP Extension Community Library
  • XML – Extensible Markup Language
  • SQL – Structured Query Language
  • MYSQL – MY ESS CUE EL
  • DDL – Data Definition Language
  • DML – Data Manipulation Language
  • DCL – Data Control Language
  • WWW – World Wide Web
  • RFC – Request For Comments
  • HTTP – Hypertext Transfer Protocol
  • HTTPS - Hypertext Transfer Protocol Secure
  • FTP – File Transfer Protocol
  • FTPS – File Transfer Protocol Secure
  • SSH – Secure Shell
  • SMTP – Simple Mail Transfer Protocol


Wednesday, April 04, 2012

Pagination Example

In View File write the following Code:
<html>
<head>
<title>Pagination Example</title>
<script src="js/jquery.tools.min.js"></script>
<script src="js/jquery.tables.first.js"></script>
<link rel="stylesheet" media="screen" href="css/pagination.css" />
</head>
<body>
<table class="paginate">
<tbody>
            <tr><td>1</td><td>Mr A</td><td>Company A</td></tr>
            <tr><td>2</td><td>Mr B</td><td>Company B</td></tr>
            <tr><td>3</td><td>Mr C</td><td>Company C</td></tr>
            <tr><td>4</td><td>Mr D</td><td>Company D</td></tr>
            <tr><td>5</td><td>Mr E</td><td>Company E</td></tr>
            <tr><td>6</td><td>Mr F</td><td>Company F</td></tr>
            <tr><td>7</td><td>Mr G</td><td>Company G</td></tr>
            <tr><td>8</td><td>Mr H</td><td>Company H</td></tr>
            <tr><td>9</td><td>Mr I</td><td>Company I</td></tr>
            <tr><td>10</td><td>Mr J</td><td>Company J</td></tr>
            <tr><td>11</td><td>Mr K</td><td>Company K</td></tr>
            <tr><td>12</td><td>Mr L</td><td>Company L</td></tr>
            <tr><td>13</td><td>Mr M</td><td>Company M</td></tr>
            <tr><td>14</td><td>Mr N</td><td>Company N</td></tr>
           
</tbody>
</table>
</body>
</html>



If you put the downloaded js file in the  js folder and css file in the css folder properly then you will get a view like below

To Run the code load this view from a controller. Run and enjoy !!!!!!!!!!!!!!!!!!


Wednesday, March 21, 2012

Validation with ajax js File

/***** Create a file jquery-1.3.2.js in a folder named scripts in the root directory ****/

Validation with ajax css file

 /*** Create a css.css file in a folder named css in the root directory *******/

.both{ font-family:Verdana, Arial, Helvetica, sans-serif;}
.both h4{ margin:0px; font-size:14px;}
.both{ float:left; margin:0 15px 0 0; padding:0px;}

#Error{
    background-image:url(../images/no.jpg);
    background-repeat:no-repeat;
    background-position:left;
    color:#FF0000;
    padding-left:33px;
    height:19px;
    padding-top:6px;
    padding-right:10px;
    }
#Success{
    background-image:url(../images/yes.jpg);
    background-repeat:no-repeat;
    background-position:left;
    color:#669933;
    padding-left:33px;
    height:19px;
    padding-top:6px;
    padding-right:10px;
    }

#customForm input{
    width: 220px;
    padding: 3px;
    float:left;
    margin-bottom:0px;
    height:20px;
    color: #000000;
    font-size: 12px;
    border: 1px solid #cecece;
}

#customForm label{
    display: block;
    color:#000000;
    float:left;
    width:100px;
    font-size:12px;
    padding-top:6px;   
}

#customForm div{
    margin-left: 10px;
    font-size: 11px;
    float:left;
}
#customForm div span{
    margin-left: 10px;
    color: #000000;
    font-size: 11px;
    float:left;
}
/* CSS Document */

Validation with ajax Controller File

/*** Create a file in Controllers name validation_username ******/



class Validation_username extends CI_Controller
    {
        function check_email_availablity()
        {
        if($_REQUEST)
            {
                $username     = $_REQUEST['username'];
                $query = $this -> db -> get_where ('personal_info', array('user_name' => $username));
              
                if($query -> num_rows() > 0) // not available
                {
                    /**** echo this -->Create a div id name Error*****/
                }
                else
                {
                    /**** echo this --> Create a div id name Success ***/
                }
              
            }

        }
    }

Validation with ajax View File

Create View in the ...application/views folder and Call this view with a Controller

I have named this view file as user_add.php.

The Code for user_add.php file is:

 /*** Show Css url 
Show js url ****/

 /******** begining of script

$(document).ready(function() {

    $('#Loading').hide();    
});

function check_username(){

    var username = $("#username").val();
    if(username.length > 0){
        $('#Loading').show();
        $.post("validation_username/check_email_availablity", {
            username: $('#username').val(),
        }, function(response){
            $('#Info').fadeOut();
             $('#Loading').hide();
            setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
        });
        return false;
    }
}

function finishAjax(id, response){

  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn(1000);
} 

*******/

/****** Body Tag will begin ***/
< Call a form and method will post *****/
User Name
/*** Creae a input type username whose name will be username onblur will be return check_username() **/
/****** Creae div tag name Info and end this div tag here ****/
 /***** Create span id Loading and in the tag loader image url will be and span tag will end ***/
/***** End Of form tag ****/
/***** End Of body tag ****/ 



Saturday, March 17, 2012

Today, Yesterday, First Date Of Month and Year

Load the date Helper First

Open ...application/config/autoload.php file and edit this file

$autoload['helper'] = array('url','form','html','date');

/*** Here I have edit the date ****/

Or

You Can Load this manually:

This helper is loaded using the following code :

$this -> load -> helper ('date');


After Loading write the code in a view and load this view within a controller and run it


 $time = time();
$todayformat = "%Y-%m-%d";
$todaydate = mdate($todayformat, $time);
echo  $todaydate; ?>

                                           
$yesterday = time()-(60*60*24);
$yesterdaydate = date("Y-m-d", mktime(0, 0, 0,date("m",$yesterday),date("d",$yesterday),date("Y",$yesterday)));
echo $yesterdaydate; ?>

                                           
$firstday = "%Y-%m-1";
$firstdaydate = mdate($firstday, $time);
echo  $firstdaydate; ?>

                                           
$first = "%Y-1-1";
$first = mdate($first, $time);
echo  $first; ?>

?>

Wednesday, March 14, 2012

Login Code With Codeigniter

Configure autoload.php
Open autoload.php from …xampp/htdocs/mysite/application/config/  and edit the following code as shown as below:

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

Configure config.php
Open config.php from …xampp/htdocs/mysite/application/config/  and edit the following code as shown as below:

$config['base_url']      = 'http://localhost/mysite/index.php/';
$config['index_page'] = '';

Configure database.php
Open database.php from …xampp/htdocs/mysite/application/config/  and edit the following code as shown as below:

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'mysite';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Code for controller: file name: login.php directory: …xampp/htdocs/mysite/application/controllers/


class Login extends CI_Controller
            {
            function __construct() {  parent::__construct();  }
            
            public function index()
                        {
                        if (isset($_GET["login_attempt"])) {
                                    $error = "Wrong User Name Or Password !!! ";
                                    $this  -> load -> view ('login_view', array('error' => $error)); }
                       
                        else {
                                     $error = "";
                                     $this  -> load -> view ('login_view', array('error' => '' )); }
                                                                                               
                        if(isset($_POST['login'])&&$_POST['login']=='Login') {
                                    $email = $_POST['email'];
                                    $password = $_POST['password'];
                                    $this -> load -> model('Model_login');
                                    $user = $this -> Model_login -> login($email,$password);
                                    }               
                        } // End Of function index
   } // End Of class Login 

Code for model: file name: model_login.php directory: …xampp/htdocs/mysite/application/models/


class Model_login extends CI_Model
            {
            function Model_login() {
                        parent::__construct(); }
           
            function login($email,$password)
                        {
                        $this -> db -> select('profile_id, email, password');
                        $this -> db -> from('profile');
                        $this -> db -> where('email = '. "'" . $email. "'");
                        $this -> db -> where('password ='. "'" . $password. "'");
                        $this -> db -> limit(1);
                       
                        $query = $this -> db -> get();
                          $row = $query -> row_array();
                       
                                    if($query -> num_rows() ==1)
                                                {
                                                redirect ('welcome');
                                                }
                                    else
                                                {
                                                header('Location: '.config_item('base_url').'login'.'?login_attempt='.urlencode("1"));
                                                }
                                    }
}
?>
Code for view: file name: login_view.php directory: …xampp/htdocs/mysite/application/views/




Email Id:

Password:




Now Open your favorite browser and type http://localhost/mysite/index.php/login and that’s our login code.