简体   繁体   中英

In Codeigniter 2, how do I use native sessions?

How do I use native sessions in CodeIgniter?

Currently I am using session_start in constants.php . Is that the right way? What are the pitfalls and is there a better way?

I am doing this because we have a PHP app and we plan to do the new coding in CI.

Also, I am looking at a good CI doc that teaches me CI basics preferably for version 2.

Thanks

Typically, using session_start and then reading/storing into $_SESSION does that. What I've historically done is to place the session_start call into my controller's constructor method: I have a single base class that inherits from CI_Controller and this handles language localization, session initialization and other silly things like P3P header settings. All my other controllers inherit from that and then they are all set.

Using native sessions is sometimes pretty useful: I've come across a few components that use native sessions that I simply didn't want to deal with patching. There are (for example) Redis session save handlers that uses native sessions: could rewrite it for CI but...why not just use what's there.

Load the session library with

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

Then you can set data using

$this->session->set_userdata((array)$userdata);

The session_start method utilizes PHP's built in session handling, which is not what is recommended for CI. Quote from the official docs:

The Session class does not utilize native PHP sessions. It generates its own session data, offering more flexibility for developers.

Have a look at http://codeigniter.com/user_guide/libraries/sessions.html - CodeIgniter is pretty well documented.

I'm using the native session lib described here . Basically this works in the same way of the CI session library, but use the native session of PHP, so you can use the functions described in the docs .

To work with Codeigniter 2, look at the discussion of the article .

Try reading up on the MY_Controller file. You can inherit from this throughout each controller and all in a nice way as per the designed methods for extending CI. Putting your SESSION stuff (and anything else cross site) in here makes the most sense.

I've written a simple CI intro article here: http://www.12devsofxmas.co.uk/2011/12/codeigniter/

If you are writing an app with lots of forms etc have a really good play around first with the framework. I've written a lot of stuff to handle templates, automatic form generation etc none of it is packaged up yet for public distribution but it's all working great for the apps we're building.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM