Rectangle 27 3

As of CodeIgniter 2.1.2

When the system/libraries/Session.php is loaded, it also loads a database to use with the sessions, if specified.

This should, in theory load the default database. For some reason, this did not work for me. I had to modify the code to specifically call the default database.

// Are we using a database?  If so, load it
if ($this->sess_use_database === TRUE AND $this->sess_table_name != '')
{
    $this->CI->load->database('default', TRUE);
}

If you would like to use a different database, just change default to the name of the database which you would like to use.

php - How do I store database sessions in CodeIgniter with multiple da...

php session codeigniter
Rectangle 27 266

Yes, the constant CI_VERSION will give you the current CodeIgniter version number. It's defined in: /system/codeigniter/CodeIgniter.php As of CodeIgniter 2, it's defined in /system/core/CodeIgniter.php

echo CI_VERSION; // echoes something like 1.7.1

Correct. It's also in the commments of that file though, so no need to write or run code just to find out the version.

In newer versions CodeIgniter.php is located in /system/core folder.

@downvoter: Why the recent downvote on this answer? Is something incorrect?

@ThomasDaugaard: A downvote implies the answer is not helpful. While I agree that the get_version wrapper is superfluous, the fact that I pointed out that this constant exists does answer the question and, I would argue, is helpful. Your point is taken, however, and I've edited to remove the get_version wrapper. Thanks for the feedback.

php - Which version of CodeIgniter am I currently using? - Stack Overf...

php codeigniter
Rectangle 27 16

I have found one way myself by looking into the CodeIgniter code: I have extended the library CI_Form_validation like: -

class MY_Form_validation extends CI_Form_validation
{
    public function getErrorsArray()
    {
        return $this->_error_array;
    }
}

I know, this is a hack, but will serve my need for the time. I hope CodeIginter team soon come up with an interface to access that array.

It's not a hack at all, that's what OOP is all about. I am walking down the exact same road, and this is my end game since I see no other alternative.

This is definitively a good solution. Shame on codeigniter for not having this functionality natively!

This doesn't return a value though. Any idea why? When I dump the $this pointer, I see that _error_array is protected. The array always returns empty.

Works! Regarding last comment, my bad. I was dumping the array before the form_validation->run() and hence the empty array.

dont call oops a hack!!

php - CodeIgniter Form Validation - Get the Result as "array" Instead ...

php codeigniter
Rectangle 27 14

That's not how CodeIgniter URLs work. It should be:

http://path/to/codeigniter/index.php/<controller>/<function>/<param>

So, in your case, it should be:

http://localhost/project1/CodeIgniter_2.1.0/index.php/hello
$config['base_url']
index.php
$config['base_url'] = 'http://localhost/project1/CodeIgniter_2.1.0/index.php';

Getting Codeigniter to work on localhost with xampp - Stack Overflow

codeigniter xampp
Rectangle 27 12

Straight from the CodeIgniter support forum:

$res = $this->db->query($str);

if (!$res) {
  // if query returns null
  $msg = $this->db->_error_message();
  $num = $this->db->_error_number();

  $data['msg'] = "Error(".$num.") ".$msg;
  $this->load->view('customers_edit_view',$data);
}

Note that you can also log Active Record errors by going into your CI app config file and setting the following:

$config['log_threshold'] = 1;

php - Codeigniter - handling errors when using active record - Stack O...

php codeigniter activerecord
Rectangle 27 44

You can set data to session simply like this in Codeigniter:

$this->load->library('session');
$this->session->set_userdata(array(
    'user_id'  => $user->uid,
    'username' => $user->username,
    'groupid'  => $user->groupid,
    'date'     => $user->date_cr,
    'serial'   => $user->serial,
    'rec_id'   => $user->rec_id,
    'status'   => TRUE
));

and you can get it like this:

$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');

php - How to save and extract session data in codeigniter - Stack Over...

php codeigniter session
Rectangle 27 30

If you're interested, there's a well-established package out there that you can add to your Codeigniter project that will handle this:

Modular Extensions makes the CodeIgniter PHP framework modular. Modules are groups of independent components, typically model, controller and view, arranged in an application modules sub-directory, that can be dropped into other CodeIgniter applications.

OK, so the big change is that now you'd be using a modular structure - but to me this is desirable. I have used CI for about 3 years now, and can't imagine life without Modular Extensions.

Now, here's the part that deals with directly calling controllers for rendering view partials:

// Using a Module as a view partial from within a view is as easy as writing:
<?php echo modules::run('module/controller/method', $param1, $params2); ?>

Typically I build a "widget" controller for each module and use it only for this purpose.

Your question was also one of my first questions when I started with Codeigniter. I hope this helps you out, even though it may be a bit more than you were looking for. I've been using MX ever since and haven't looked back.

Make sure to read the docs and check out the multitude of information regarding this package on the Codeigniter forums. Enjoy!

php - CodeIgniter: Load controller within controller - Stack Overflow

php codeigniter
Rectangle 27 6

You shouldn't need to do this, codeigniter does it all for you.

If you wish to get the session id you can do so by calling:

$session_id = $this->session->userdata('session_id');

However you can work around it: ( Note this post is 3 years old and I'm unsure if it's still necessary )

php - Setting Session_id in CodeIgniter - Stack Overflow

php session codeigniter
Rectangle 27 16

To do it codeigniter way, place your custom classes in libraries folder of codeigniter. And then use it by adding that class as library in your controller like this:

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

class Someclass {

   public function some_function()
   {
   }
}

/* End of file Someclass.php */

using in controller:

$this->load->library('someclass');

php - Loading custom classes in CodeIgniter? - Stack Overflow

php codeigniter
Rectangle 27 17

get_instance() is a function defined in the core files of CodeIgniter. You use it to get the singleton reference to the CodeIgniter super object when you are in a scope outside of the super object.

I'm pretty sure it's defined in base.php or something similar.

php - explain $CI =& get_instance(); - Stack Overflow

php codeigniter
Rectangle 27 17

get_instance() is a function defined in the core files of CodeIgniter. You use it to get the singleton reference to the CodeIgniter super object when you are in a scope outside of the super object.

I'm pretty sure it's defined in base.php or something similar.

php - explain $CI =& get_instance(); - Stack Overflow

php codeigniter
Rectangle 27 2

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

This is the exact issue i have faced, before i posted. In my case also there is no error message displayed, only blank page comes. I have given permission to CI folder in ubantu and restarted the apache server and it works.

php - Codeigniter displays a blank page instead of error messages - St...

php codeigniter
Rectangle 27 14

Of course, turning off the CSRF protection means you are left open to CSRF attacks.

Thanks, it helps me a lot with a problem trying to upload files using AJAX requests, with Plupload and Codeigniter.

I agree with HighlyIrregular this doesn't really solve the problem, it works around it and leaves OP open to CSRF attacks. JoeMoe1984 and Jhourlad Estrella have the better answers. We shouldn't be encouraging less-secure coding/development practices.

It is obvious security is must so that disable CSRF is not recommended. When we enable the CSRF in CI, in every forms it it adds something like this <input type="hidden" name="csrf_token" value="4ac7a11a8239660afaa87cb48f2694e2" style="display:none;" /> but the above error occurs when we use <form> .... </form> it because CI don't add that hidden input when we use <form> .... </form> and when we submit form without the CSRF token while CSRF enabled it give the above error. All you have to do is use <?php echo form_open();?> and <?php echo form_close();?>

codeigniter - Action you have requested is not allowed error - Stack O...

codeigniter pyrocms
Rectangle 27 9

Thanks to http://codeigniter.com/forums/viewthread/73804/#366081 and some bits of information from some CI folk that I follow on twitter (I asked em): Eric Barnes, Dan Horrigan, Phil Sturgeon and Zack Kitzmiller, I found a solution. If you are a CodeIgniter n00b like me, you may like to follow these guys.

I deleted init.php and config.php, then jammed the following into the bottom of my CI's config.php (I am also autoloading from a custom library called mylibrary).

function multi_auto_require($class) {
if(stripos($class, 'CI') === FALSE && stripos($class, 'PEAR') === FALSE) {
    foreach (array('flourish', 'mylibrary') as $folder){
        if (is_file(APPPATH."../auxengines/{$folder}/{$class}.php")){
            include_once APPPATH."../auxengines/{$folder}/{$class}.php";
        }
    }
}
}

I had to add 'MY' and 'MX' to that, as I'm using the HMVC extension, just in case anyone finds this answer doesn't quite solve the problem.

Using the PHP spl_autoload_register() with Codeigniter - Stack Overflo...

php codeigniter autoload spl-autoload-register
Rectangle 27 2

this is a singleton structure to understand how the codeigniter loads the libraries and classes

<?php

/*
====================================
start of the loader class
====================================
*/
class Loader {


  protected function _init_class($class){
    $C = Controller::get_instance();
    $name = strtolower($class);
    $C->$name = new $class();
  }

  public function _class($library){
    if(is_array($library)){
      foreach($library as $class){
        $this->library($class);
      }
      return;
    }

    if($library == ''){
      return false;
    }

    $this->_init_class($library);
  }

  public function view ($param) {
     echo $param;
  }
}
/*
===============================
 End of the loader class
==============================
*/

/*
===============================
 start of core controller class
==============================
*/

class Controller {

  private static  $instance;

  function __construct () {
    self::$instance = $this;
    $this->load = new Loader();
  }


  public static function get_instance(){
    return self::$instance;
  }
}
/*
===============================
end of the core controller class
=================================== 
*/

/*
 ====================================================
  start of library sections (put all your library classes in this section)
=====================================================
*/

class MyLibrary {

 private $c;

 function __construct() {
   $this->c = Controller::get_instance();
 }

 function say($sentence) {
   $this->c->load->view($sentence);
 }
}
/*
 ====================================================
  End of the library sections
====================================================
*/

/*
 ============================================
  start of controller section (put all your controller classes in this section)
 ===========================================
*/

class Foo extends Controller {

  function __construct () {
    parent::__construct();
    $this->load->_class('MyLibrary');
  }

  function bar() {
    $this->mylibrary->say('Hello World');
  }
}


/* 
 ==========================================
  End of the controller sections
 ==========================================
*/

$foo = new Foo();
$foo->bar();

php - explain $CI =& get_instance(); - Stack Overflow

php codeigniter
Rectangle 27 2

this is a singleton structure to understand how the codeigniter loads the libraries and classes

<?php

/*
====================================
start of the loader class
====================================
*/
class Loader {


  protected function _init_class($class){
    $C = Controller::get_instance();
    $name = strtolower($class);
    $C->$name = new $class();
  }

  public function _class($library){
    if(is_array($library)){
      foreach($library as $class){
        $this->library($class);
      }
      return;
    }

    if($library == ''){
      return false;
    }

    $this->_init_class($library);
  }

  public function view ($param) {
     echo $param;
  }
}
/*
===============================
 End of the loader class
==============================
*/

/*
===============================
 start of core controller class
==============================
*/

class Controller {

  private static  $instance;

  function __construct () {
    self::$instance = $this;
    $this->load = new Loader();
  }


  public static function get_instance(){
    return self::$instance;
  }
}
/*
===============================
end of the core controller class
=================================== 
*/

/*
 ====================================================
  start of library sections (put all your library classes in this section)
=====================================================
*/

class MyLibrary {

 private $c;

 function __construct() {
   $this->c = Controller::get_instance();
 }

 function say($sentence) {
   $this->c->load->view($sentence);
 }
}
/*
 ====================================================
  End of the library sections
====================================================
*/

/*
 ============================================
  start of controller section (put all your controller classes in this section)
 ===========================================
*/

class Foo extends Controller {

  function __construct () {
    parent::__construct();
    $this->load->_class('MyLibrary');
  }

  function bar() {
    $this->mylibrary->say('Hello World');
  }
}


/* 
 ==========================================
  End of the controller sections
 ==========================================
*/

$foo = new Foo();
$foo->bar();

php - explain $CI =& get_instance(); - Stack Overflow

php codeigniter
Rectangle 27 2

I'm not sure if I understood, but.

If you have a string date, as in your example, you could transform it in a Date Object, than you can format as you want.

$date =  '2014-12-17';
$dateObj = date_create($date);

echo date_format($dateObj, 'Y-m-d'); // will show 2014-12-17
echo date_format($dateObj, 'd-m-Y'); // will show 17-12-2014

php - converting date in to same format as it was before in codeignite...

php codeigniter date time strtotime
Rectangle 27 5

Actually that are two pair of shoes: PHP Sessions and codeigniter sessions. It is good to know about the major differences and that is basically everything as in codeigniter the sessions did re-invent the wheel for large parts plus adding some features.

So before you continue it's probably worth to take a look into the Session chapter in the PHP manual , PHP's build in session support is pretty powerful - but has not an object interface.

For example to store PHP sessions into the database (default is the file-system), that is supported by a so called session save handler. Some PHP extensions offer a save-handler (e.g. memcache). Just to lighten your mind, this works with anything compatible with the memchache protocol, e.g. MySQL. But that is just one example. If you are looking for a session class, that is not related to native PHP sessions, add "PHP 3" to your search because before version 4, PHP had no native sessions and sure, others needed sessions, so they wrote their own libraries.

Okay, to be sane, using PHP today, looking for sessions and saying that one don't want to touch PHP sessions is: just stupid. You might not want to touch the file-system, then store to cookies. You might not want to store to cookies, store to any store that is fast and server-side: memcached, mysql, couchdb, ssd file-system. Whatever. PHP native sessions are very flexible here:

You can as well write your own user-land session save handler and store your session into the database. Actually any key-value store will do: The key is the session id, and the value is the encoded (serialized) session data. That is one binary string.

As written next to the re-invention of the wheel codeigniter does, there are some features you might be looking for. Basically you can always take a look into the source-code of the session component of codeiginiter, it's not that complex. With a good IDE you can pick the stuff you want to inspect or just view it as inspiration.

One feature is the meta-data codeigniter assigns to a session which for example is the remote address, the session start time (very useful) and the last activity (useful, too). You can pretty easily mimic that your own by storing this into the session each time you start (example below). For that you can create your own session object. The following is only a bare example, but it already has some nice features:

  • Meta-data like remote IP, creation and last activitiy timestamp.
  • Destroying of cookies if applicable.
$session = new Session();
$session['foo'] = 'bar';
$session->destroy(); // yes, full destroy
/**
 * Session class
 *
 * @license MIT
 * @license-year 2012
 * @license-copyright-holder hakre <http://hakre.wordpress.com>
 */
class Session implements ArrayAccess
{
    private $meta = '__meta';
    private $started;

    public function __construct()
    {
        if (ini_get('session.auto_start')) {
            $this->started = true;
            $this->start();
        }
    }

    public function start()
    {
        $this->started || session_start();
        (isset($_SESSION[$this->meta]) || $this->init())
            || $_SESSION[$this->meta]['activity'] = $_SERVER['REQUEST_TIME'];
        $this->started = true;

    }

    /**
     * write session data to store and close the session.
     */
    public function commit()
    {
        session_commit();
    }

    public function destroy()
    {
        $_SESSION = array();
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        session_destroy();
    }

    public function get($name, $default = NULL)
    {
        return isset($_SESSION[$name]) ? $_SESSION[$name] : $default;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return session_name();
    }

    private function init()
    {
        $_SESSION[$this->meta] = array(
            'ip'       => $_SERVER['REMOTE_ADDR'],
            'name'     => session_name(),
            'created'  => $_SERVER['REQUEST_TIME'],
            'activity' => $_SERVER['REQUEST_TIME'],

        );
        return true;
    }

    /**
     * Whether a offset exists
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     * @param mixed $offset
     * @return boolean true on success or false on failure.
     * The return value will be casted to boolean if non-boolean was returned.
     */
    public function offsetExists($offset)
    {
        $this->started || $this->start();
        return isset($_SESSION[$offset]);
    }

    /**
     * Offset to retrieve
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     * @param mixed $offset
     * @return mixed Can return all value types.
     */
    public function offsetGet($offset)
    {
        $this->started || $this->start();
        return $this->get($offset);
    }

    /**
     * Offset to set
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     * @param mixed $offset
     * @param mixed $value
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        $this->started || $this->start();
        $_SESSION[$offset] = $value;
    }

    /**
     * Offset to unset
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     * @param mixed $offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($_SESSION[$offset]);
    }
}

So to summarize: If you use PHP sessions, you use PHP sessions. They are powerful, but you might want to add your handling on top. The exemplary Session class above takes care about the session life-cycle: Init, Update and destruction. PHP iteself takes care of starting the factual session and also about saving it. Naturally, you can add a class for the session storage as well, but if you are concerned about performance and simplicity, normally this can all be configured within php.ini.

  • Regenerating session IDs (PHP supports that, so easy to add to the class or just call PHP's function)
  • Copying data from one session to another (PHP does not support this easily, it's worth to wrap such a feature into the session class if you need it - codeigniter does not have that, too)
  • Obtaining status if a session currently runs or not (the global PHP session). The Session class is a good place to add that if and only if you need it. You find the code in a related question: How to tell if a session is active?

So, find out what you need. Implement as that, it can be pretty trivial. Write your own Session class wisely, feel free to use that one above as a base and add the features you need.

You're welcome. The class is pretty quickly written, so add the stuff you're missing (and ask if something is not clear to you). Also knowing about the PHP ini settings is a key point here, codegniter puts session configuration into their config file, PHP has it's own config file (php.ini).

PHP Session class similar to CodeIgniter Session Class? - Stack Overfl...

php codeigniter session
Rectangle 27 3

pl's solution will defenitely work but you would need to edit all of your controllers. I'd like to point you to another approach. CodeIgniter provides a Hook functionality (not the best, but still better than nothing). Hooks provide the functionality to execute code before certain actions in the CodeIgniter core happen.

For your purpose I'd suggest to use the 'post_controller_constructor' hook which will be executed after a controller gets instantiated, but before any method calls are happening.

$hook['post_controller_constructor'] = array(
    'class'    => 'Auth',
    'function' => 'has_permission',
    'filename' => 'Auth.php',
    'filepath' => 'hooks',
);

By grabbing an instance of CodeIgniter ($ci =& get_instance()) you will be able to use all the functionality of the framework inside your class you pass to your hook (just like writing your own CI Library). So you can check there for sessions and handle user permissions.

ruuter called my attention to use post_controller_constructor instead of pre_controller which allows the usage of get_instance() (which would not be available using pre_controller). The downside of using post_controller_constructor is, that the controllers constructor will always be called before checking for permissions which might cause trouble in certain situations.

It should be noted that $ci =& get_instance() is NOT available in pre_controller hook. You can use post_controller_constructor hook to get CI instance. This hook is called after controller is instantiated, but prior to any method calls happening.

Access control issue in CodeIgniter - Stack Overflow

codeigniter access-control
Rectangle 27 2

At first download openid.php and put in your codeigniter root folder.

1. copy the code and save as ..../controller/logingoogle.php

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

class LoginGoogle extends CI_Controller 
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('login_model');
    }

    public function index()
    {
        require_once 'openid.php';
        $openid = new LightOpenID("localhost");
        $openid->identity = 'https://www.google.com/accounts/o8/id';
        $openid->required = array(
            'namePerson/first',
            'namePerson/last',
            'contact/email',
            'birthDate', 
            'person/gender',
            'contact/postalCode/home',
            'contact/country/home',
            'pref/language',
            'pref/timezone',  
        );
//  $openid->returnUrl = 'http://localhost/login_thirdparty/login_google.php';

    $openid->returnUrl = 'http://localhost/login_thirdparty/codeigniterlogin/index.php/logingoogle/loginAuth';

//  echo '<a href="'.$openid->authUrl().'">Login with Google</a>';

        $data['openid'] = $openid;
        $this->load->view('googleLoginView', $data);
    }

    public function loginAuth()
    {
        $this->login_model->index();
    }
}

2. copy the code and save as ..../views/googleLoginView.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Login using google account</title>
</head>
<body>
    <a href = "<?php echo $openid->authUrl(); ?>" > Loging Using google account </a>
</body>
</html>

3. copy the code and save as ..../models/login_model.php

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

class Login_model extends CI_Model 
{
    public function index()
    {
        $openid = new LightOpenID("localhost");

        if($openid->mode)
        {
            if($openid->mode == 'cancel')
            {
                echo "User has canceled authentication !";
            }
            elseif($openid->validate())
            {
                $data = $openid->getAttributes();
                $email = $data['contact/email'];
                $first = $data['namePerson/first'];
    //          header("Location: http://speechwithmilo.com/speechtherapy/adminpanel/");
                echo "Identity : $openid->identity <br />";
                echo "Email : $email <br />";
                echo "First name : $first";
                echo "<pre>"; print_r($data); echo "</pre>";

//              echo "<meta http-equiv = 'refresh' content = '0; url=http://speechwithmilo.com/speechtherapy/adminpanel/'>";
            }
            else
            {
                echo "The user has not logged in";
            }
        }
        else
        {
            echo "Go to the login page to logged in";
        }
    }
}

I used your solution but encountered an error. Please take a look at my question here. stackoverflow.com/questions/22173781/

php - Login with Google account in CodeIgniter with OpenID - Stack Ove...

php codeigniter openid