Why your session variables fail in Codeigniter: How to fix them

If you are familiar with codeigniter and have done a full application using it you will find it a bit weird that the session class does not actually create a session. What do I mean? Yes I mean that the session class saves the data in browser cookies you can prove that by trying to print the session variables and you may get some very crazy errors.

print_r($_SESSION);

You may get a PHP error notice: variable _SESSION not initialized or something close to that and you go checking if your session library is loaded which i is and you wonder where did the session variables go.

Someone may ask why do you need the sessions is the session class not very great and useful? Well I have a practical scenario:
Take a case where you want to force the users to enter a valid captcha for your forms and you do not want to use the barbaric methods of codeigniter of storing captchas and want to use a great captcha generator such as cool captcha in your forms.

The challenge is simple the captcha generator stores the text of the image captcha in a session variable and during validation in codeigniter you would need your callback validator method to access the session variable to perform validation.

Now in this case you create your form and your captcha creates a cool image but you cannot access the session information and so you cannot validate the input. If you canno validate the captcha the form would be useless as any robot can have fun.

Now for the fix:

The fix is really easy. If you have used some codeigniter CMS systems such casino as PyroCMS you will notice that you do not get such problems so how do we fix it?

To start with since codeigniter does not use the real php sessions you can assume that a session is never started. This being the case you simply need to add the line below to the constructor of the Class you need to use sesssions and voila! All your sessions will work perfectly.

session_start();

I was mad the first time I got this error I thought codeigniter was clearing the session variable which if it did would cause me much trouble and I would be moving away from codeigniter. Thanks to all who share ideas the problem was simply back to basics of php.

To all you codeigniter lovers high five for creating applications with the easiest php framework around that is fully documented and light.

Both comments and pings are currently closed.

Comments are closed.

Powered by WordPress | Designed by: NewWPThemes