Monday, 12 September 2011

How to Accessing CodeIgniter Session Data using External Scripts


we have the need to access CodeIgniter session data outside of our CI installation, more specifically for a WordPress installation. CodeIgniter, as most developers should already know, stores it’s session data in a database and uses a cookie to refer to the data, as opposed to storing this data inside of the PHP default $_SESSION superglobal.
The CodeIgniter cookie stored on the local computer isn’t just a random hash representing the session stored on the server, as it is with PHP’s $_SESSION. It is actually a serialized object representing the hash, along with the users IP address and useragent, which provides a second level of security as CodeIgniter will see if this cookie really does belong to the user who has it. The data is also hashed and a signature is provided with the cookie which prevents forgery.
So, to access this data, we’ll need to get the cookie from the user, remove slashes if our server has magic_quotes enabled, unserialize the data, run a SQL query to grab the data using the cookie hash we found, then unserialize the data returned from the database. Easy, huh?
Here is the code. You’ll need to add some extra security measures to make sure the cookie doesn’t contain SQL injection, along with checking the cookie user agent data against the data provided by the browser, but this is the quick and dirty version:
require_once("config.php");
$cisess_cookie = $_COOKIE['ci_session'];
$cisess_cookie = stripslashes($cisess_cookie);
$cisess_cookie = unserialize($cisess_cookie);
$cisess_session_id = $cisess_cookie['session_id'];

$cisess_connect = mysql_connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD);
if (!$cisess_connect) {
 die("<div class=\"error\">" . mysql_error() . "</div>");
}
$cisess_query = "SELECT user_data FROM ci_sessions WHERE session_id = '$cisess_session_id' LIMIT 1";

mysql_select_db(MYSQL_DATABASE, $cisess_connect);
$cisess_result = mysql_query($cisess_query, $cisess_connect);
if (!$cisess_result) {
 die("Invalid Query");
}
$cisess_row = mysql_fetch_assoc($cisess_result);
$cisess_data = unserialize($cisess_row['user_data']);
print_r($cisess_data);

[+/-] Read More...

how to create session database in code igniter


Code Igniter bundles a session class, working with cookies. Unfortunately, this class stores session data directly inside the cookie, thus allowing the client to see and edit those data. Here is a replacement class that stores data in the database.
(note: the original Code Igniter Session class can use a database, but only for validation purposes. The actual data is stored in the cookie itself)

1/ Using the class

This class works with the new CodeIgniter v1.4 ! (and 1.5)
The usage is the same as the bundled Code Igniter session class. So you use it like :
$this->db_session->set_userdata('info''some thing interesting'); 
and get back data like :
$foo $this->db_session->userdata('info'); 
This class supports so called “flashdata” variables, which are variables that persist only for the next request. More information at Native session.

2/ Configuration

This class uses the same configuration directives than the original session class. So don’t forget to set inside your ‘config.php’ :
$config['sess_cookie_name''mysite';$config['sess_expiration'7200;$config['sess_use_database'TRUE;$config['sess_table_name''ci_sessions';$config['sess_match_ip'TRUE;$config['sess_match_useragent'FALSE;$config['cookie_prefix'"";$config['cookie_domain'"";$config['cookie_path'"/"

3/ Database

Here is the table schema needed by the new session class :
CREATE TABLE IF NOT EXISTS `ci_sessions` (session_id varchar(40) DEFAULT '0' NOT NULL,ip_address varchar(16) DEFAULT '0' NOT NULL,user_agent varchar(50NOT NULL,last_activity int(10unsigned DEFAULT 0 NOT NULL,session_data text default '' not null,PRIMARY KEY (session_id)
); 

4/ Installing the package

Just get the zip File:db sessions.zip .

Move the file DB_Session.php in your application/libraries directory, and (for CI < 1.5) the file init_db_session.php inside yourapplication/init directory. Then use the autoload feature of Code Igniter : open your “autoload.php” configuration file and add “db_session” in the core autoload array :
For ci < 1.5:
$autoload['core'= array('database','db_session'); 
For ci > 1.5
$autoload['libraries'= array('database''db_session'); 
For CI 1.5 the init_db_session.php files is not needed.  Simply rename the DB_Session.php file to Session.php and change the class name constructor function to Session. Then of course autoload or load session.

5/ Inside working

Using this class, the cookie only stores a unique session identifier. Everything else is matched from the database.

6/ Issues

Some people report an issue where error messages are shown when this library is being used the first time. The error messages refer to the Filename: libraries/DB_session.php and include
- Message: Undefined index: user_agent
- Message: Undefined index: ip_address
- Message: Undefined index: session_id
The fix requires changing FALSE to TRUE in the line $config[‘sess_use_database’]  = TRUE; in config.php

[+/-] Read More...

Ajax image upload in code igniter


Codeignier Ajax File Upload module is easy and simple and build with Codeigniter File Uplaod Library and  AjaxFileUpload – Jquery Plugin .
File: ajaxupload.php (Contorller).
function doupload(){
$uploadFile = uri_assoc(‘fld’,2);
$config['upload_path'] = ‘./uploads/’;
$config['allowed_types'] = ‘gif|jpg|png’;
$this->load->library(‘upload’, $config);
if ( ! $this->upload->do_upload($uploadFile))
{
$error = array(‘error’ => $this->upload->display_errors());
$this->load->view(‘upload_form’, $error);
}
else
{
$data = array(‘upload_data’ => $this->upload->data());
$this->load->view(‘upload_success’);
}
}
File: upload_form.php(views).
<script type=”text/javascript” src=”<?=base_url()?>/ajaxfileupload.js”></script>
<input type=”file” name=”uploadfile”  id=”uploadfile” />
<intpy type=”button” name=”upload” id=”upload”  value=”Upload” />
<script>
$(function(){
$(‘#upload ‘).click(function(){
$.ajaxFileUpload
(
{
url:  “ajaxupload/doupload/fld/uploadfile”,
secureuri:false,
fileElementId: ‘uploadfile’,
dataType: ‘json’,
success: function (data, status)
{
if(typeof(data.error) != ‘undefined’)
{
if(data.error != ”)
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(e);
}
}
);
});
});
</script>


[+/-] Read More...

Code Igniter Image Uploader / File Uploader – Multiple


Creating an image uploader or file uploader is a big problem in web domain coding. Code Igniter Made it easy for you. It uses two classes File Uploading Class and Image Manipulation Class. Great Programme made for save the life of a web developer. I Got a detailed post from Jefim Boressov (The Mighty Web Developer)’s Blog. And It was Great. I am copying the code for my future reference. Thanks Jefim.

Image / file upload with CodeIgniter

Image upload is difficult for web developer. And even though CI has a lot to offer (in the means of documentation) it still lacks a direct copy-paste code on their website so that people can just put it into their controller and use away.
Here we will have:
  • Image upload form with 5 images
  • And a controller function that will upload those
  • Thumbnails will be there too 
Ok, lets start with the HTML form code, it is very basic:
views/upload_form.php
<form method="post" action="uploader/go" enctype="multipart/form-data">
  <input type="file" name="image1" /><br />
  <input type="file" name="image2" /><br />
  <input type="file" name="image3" /><br />
  <input type="file" name="image4" /><br />
  <input type="file" name="image5" /><br />
  <input type="submit" name="go" value="Upload!!!" />
</form>
And now the controller:
controllers/Uploader.php
class Uploader extends Controller {
  function go() {
    if(isset($_POST['go'])) {
      /* Create the config for upload library */
      /* (pretty self-explanatory) */
      $config['upload_path'] = './assets/upload/'; /* NB! create this dir! */
      $config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
      $config['max_size']  = '0';
      $config['max_width']  = '0';
      $config['max_height']  = '0';
      /* Load the upload library */
      $this->load->library('upload', $config);

      /* Create the config for image library */
      /* (pretty self-explanatory) */
      $configThumb = array();
      $configThumb['image_library'] = 'gd2';
      $configThumb['source_image'] = '';
      $configThumb['create_thumb'] = TRUE;
      $configThumb['maintain_ratio'] = TRUE;
      /* Set the height and width or thumbs */
      /* Do not worry - CI is pretty smart in resizing */
      /* It will create the largest thumb that can fit in those dimensions */
      /* Thumbs will be saved in same upload dir but with a _thumb suffix */
      /* e.g. 'image.jpg' thumb would be called 'image_thumb.jpg' */
      $configThumb['width'] = 140;
      $configThumb['height'] = 210;
      /* Load the image library */
      $this->load->library('image_lib');

      /* We have 5 files to upload
       * If you want more - change the 6 below as needed
       */
      for($i = 1; $i < 6; $i++) {
        /* Handle the file upload */
        $upload = $this->upload->do_upload('image'.$i);
        /* File failed to upload - continue */
        if($upload === FALSE) continue;
        /* Get the data about the file */
        $data = $this->upload->data();

        $uploadedFiles[$i] = $data;
        /* If the file is an image - create a thumbnail */
        if($data['is_image'] == 1) {
          $configThumb['source_image'] = $data['full_path'];
          $this->image_lib->initialize($configThumb);
          $this->image_lib->resize();
        }
      }
    }
    /* And display the form again */
    $this->load->view('upload_form');
  }
}

[+/-] Read More...

How to solve session login problem in code igniter in IE

Since the CodeIgniter sessions work fine in some IE7 browsers and fail miserably in others there’s no definite fix for this problem. One thing that might be causing it is the underscore (_) in the cookie name that stores the session variables. The default CI cookie name is ‘ci_session’. Try removing the underscore and see how that works for you (did it for me).

$config['sess_cookie_name'] = 'cisession'; // note: no more underscore

If that didn’t do the trick for you you might try checking you’re server’s time settings. When cookies are being stored they are given a lifetime. It could be that you’re server’s time is a few hours behind and thus cookies will be removed immediately since their lifetime is already over.

The last, but best thing you can do is to drop the CodeIgniter session library and start using PHP’s default session handling using session_start(), $_SESSION[], unset and session_destroy. Have a look at the CodeIgniter Native Session Library if you really need to use a library to handle your sessions.

[+/-] Read More...