6

In my codeigniter project i have added KCK finder.

it needs some of session values which is controlled by codeigniter. how can i access CI session values from external files ?

balaphp
  • 1,306
  • 5
  • 20
  • 40

7 Answers7

6
<?php
    ob_start();
    include('index.php');
    ob_end_clean();
    $CI =& get_instance();
    $CI->load->library('session'); //if it's not autoloaded in your CI setup
    echo $CI->session->userdata('name');
?>
Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108
  • This don't work for me: Your system folder path does not appear to be set correctly. Please open the following file and correct this: index.php – Jorge Olivares Aug 23 '17 at 19:31
  • This don't work for me too. This `include('index.php');` file, i have included it from the external_codeigniter folder. Can you help on this? – Dan Feb 13 '18 at 10:23
  • Great answer but lacking some clarifications: 1. Copy the CI index.php file into the new folder 2. Open index.php and change `application folder path` and `system folder path` accordingly. – mutiemule Dec 23 '18 at 22:15
4

If you are looking to access the sessions (and they are file based) from outside of codeigniter and you do not want to load CI, you can do this:

define('ENVIRONMENT', 'development');

$ds = DIRECTORY_SEPARATOR;
define('BASEPATH', dirname(dirname(dirname(__FILE__))));
define('APPPATH', BASEPATH . $ds . 'application' . $ds);
define('LIBBATH', BASEPATH . "{$ds}system{$ds}libraries{$ds}Session{$ds}");

require_once LIBBATH . 'Session_driver.php';
require_once LIBBATH . "drivers{$ds}Session_files_driver.php";
require_once BASEPATH . "{$ds}system{$ds}core{$ds}Common.php";

$config = get_config();

if (empty($config['sess_save_path'])) {
    $config['sess_save_path'] = rtrim(ini_get('session.save_path'), '/\\');
}

$config = array(
    'cookie_lifetime'   => $config['sess_expiration'],
    'cookie_name'       => $config['sess_cookie_name'],
    'cookie_path'       => $config['cookie_path'],
    'cookie_domain'     => $config['cookie_domain'],
    'cookie_secure'     => $config['cookie_secure'],
    'expiration'        => $config['sess_expiration'],
    'match_ip'          => $config['sess_match_ip'],
    'save_path'         => $config['sess_save_path'],
    '_sid_regexp'       => '[0-9a-v]{32}',
);


$class = new CI_Session_files_driver($config);

if (is_php('5.4')) {
    session_set_save_handler($class, TRUE);
} else {
    session_set_save_handler(
        array($class, 'open'),
        array($class, 'close'),
        array($class, 'read'),
        array($class, 'write'),
        array($class, 'destroy'),
        array($class, 'gc')
    );
    register_shutdown_function('session_write_close');
}
session_name($config['cookie_name']);
session_start();
var_dump($_SESSION);
Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27
  • I have been searching for solutions for hours, and this is the only one works perfectly. This one works outside of CI project perfectly. THANK YOU. – Frank Sep 13 '18 at 03:06
3

As more cleaning of '@Ben Swinburne' answer:

  1. Copy the CI index.php file and rename it (i.e. index_for_external_app.php).

  2. Open the new PHP file (index_for_external_app.php) and then edit the following variables to the external path:

    -$application_folder  
    -$system_path  
    [i.e. $system_path = '../../system';]  
    
  3. Call the created PHP file from your external system

    //include the CI index file within ob_start to prevent display other html
    ob_start();
    require('../../index_for_external_app.php');///You should edit this path
    ob_end_clean();
    
    //print the session variable for testing
    echo '<pre>';
    print_r($_SESSION);
    echo '</pre>';
    
Azametzin
  • 5,223
  • 12
  • 28
  • 46
Moh Rawaf
  • 31
  • 2
0

Bens answer with include('index.php') and getting CI instance is not bad but in my situation these actions are too slow.

As i have codeigniter set to use files i made this solution which is a bit faster:

function CIsession()
{
    $pathToSessionFiles = 'path/to/files/set/in/codeigniter/config/';

    $h = md5($_SERVER['REMOTE_ADDR']); // $config['sess_match_ip'] = TRUE;
    foreach( glob($pathToSessionFiles . '*' ) as $f )
    {   
        if( strpos($f, $h) ) { $s[ $f ] = filemtime($f); }
    }
    arsort($s);
    $s = array_keys($s);
    $s = reset($s);
    $s = file($s);
    $s = reset($s);
    $s = explode(';', $s);
    foreach($s as $k => $v)
    {
        $s[$k] = str_getcsv($v, ":", '"');
        $s[$k][0] = substr(reset($s[$k]), 0, strpos(reset($s[$k]), '|'));

        $s[reset($s[$k])] = end($s[$k]);
        unset($s[$k]);
    }

    return $s;
}

Hope it helps someone!

0

Two solutions comes to mind (that don't involve decoding CI's cookies)

1) Copy them to regular PHP sessions, when you assign the inside CI:

$_SESSION['name'] = $this->session->userdata('name');

So you have it available to every php file on your server; I believe this is the fastest solution.

2) save the sessions to database and connect to it to retrieve the values.

Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
  • i got a solution from this site http://www.renownedmedia.com/blog/accessing-codeigniter-session-data-using-external-scripts/ its works but its needs some modification. – balaphp Oct 28 '11 at 08:08
0

Hi just before i got this code by googling.

     //path to your database.php file   
     require_once("../frontend/config/database.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($db['default']['hostname'], $db['default']      ['username'], $db['default']['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'";

     mysql_select_db($db['default']['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 all session values 
     print_r($cisess_data);
balaphp
  • 1,306
  • 5
  • 20
  • 40
0

I am using an external login app and wanted to use data from CI sessions. I found this information http://codeigniter.com/forums/viewthread/86380/ on how to do that without running anything from the CI framework. For me this is ideal as it will keep any incompatibilities from causing issues.

In case you have issues extracting the information from the link:

  1. If using ci session cookies then get the session cookie only.
  2. If using ci session with database then get the session cookie and query for a match in the database in the ci_session table to verify session.
  3. Use data and add data as needed in cookie (and in database if using database session).
Demolishun
  • 1,592
  • 12
  • 15