In Codeigniter 2, how do I use native sessions? - php

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.

Related

What is the best solution( especially for performance and clean code ) to use __autoload in codeigniter?

I will use __autoload function in Codeigniter, but I'm not sure what is the best way.
I have read Phil Sturgeon's article and he uses at the bottom of config.php and
I asked to my friend, he uses in index.php
But I think they are not clean usage.
I want to use it in hook but I read this answer( last answer in the page ) How to add autoload-function to CodeIgniter?
and there is a negative vote on it.
Is to use in hook not good solution?
Codeigniter's autoload system is the easier way if you're using that framework: you just add the classname as index of an array and you're set.
Technically, it's not a "proper" autoloader, is a registry that checks if the class has already been instanciated in the static array of classes and, if not, adds it. In the way CI works it's efficient enough, and more important: is way easier for the user, compatible with any php version, and you don't need to code anything to implement it.
A proper autoloader using the __autoload() magic method, or better with spl_autoload_register() means you need to separate your loaded classes from what loads CI, and you need to implement it manually.
For future-ready applications check the PSR-0 standard which gives you indications on how to build a "standard" autoloader to be used to load classes in what's becoming the trend in PHP world: package management and distribution, similar to what other languages already do.

How to manage sessions and users with CodeIgniter?

I'm in the middle of moving my site into the CodeIgniter framework. I've never used a MVC framework before so this is a big step.
In my old site, each page would have include("session_handler.php"); at the top of each page. This script would check session variables, authenticate sessions and store stuff in the database.
Is there a way I can have this script automatically include in every page? Can I specify it in the config? Does CI maybe have an internal way of dealing with sessions that is superior to my method?
Code Igniter has a Session class you can use.
It also has an autoload functionality.
Those two things should cover your requirements I think...
If you need additional validation to the session, you can either extend the core session class (which may be asking too much if you're only starting on the framework) or you can create your own library and auto-load it right after the session one to run some additional code..

CodeIgniter: placing PHP functions?

I'm still quite new to CodeIgniter and I was wondering, where should I place my PHP functions that has nothing to do with Controllers and Views, for example, a function that access a local file.
Thank you.
Do not use plugins as they are removed from CI 2.0 and you will have to convert them.
A group of functions that do not require data interaction should be placed in a helper.
Put loose functions into helpers. Group similar functions together into a helper and give it a meaningful file-name. Once the helper is loaded the functions can be used as though it were a require_once() or include.
If you have a class which has ostensibly "nothing to do" with Codeigniter, these can usually be converted into libraries with minimal or no effort.
Plugins are being taken out in CI 2.0, as Phil Sturgeon said, in favour of helpers and libraries. Which is a good thing, I think. Never had much need for 'plugins'.
You should place them in Controller, in controller you can put in even your own custom functions.
There are plugins and helpers directories where you can place files that include 'global' functions that are shared across your entire application.
That said, you should think before doing this, it may well make more sense to place the file in a model, if you are working with data stored on the file system.

User authentication with CodeIgniter

I am writing a web application using PHP. I want to use the MVC pattern for this, and decided to go with CodeIgniter. My application will have some pages which will require authentication, and some pages won't. I want to design this in a very generic way, so that there should be no code duplication. Can any one point to some good "design/class structure" for this?
Write a custom library that you can autoload in your code igniter app on every page view. It should have functions that:
Authenticate the user ie. check if a user is logged in or not
Log you in ie. set a session variable or something
Log you out
Then in your controller classes you can do a call to the authentication function in the constructor then depending on the outcome continue as normal or redirect them to a login screen with an access denied message.
Do a search on the code igniter wiki for 'authentication' and there are a number of results that may help: http://codeigniter.com/wiki/
"Ion Auth" is lean, well-programmed, somewhat widely used and is actively maintained.
http://github.com/benedmunds/CodeIgniter-Ion-Auth
If by "some pages" you mean some controllers (the gateway to your views), then you may want to investigate controller inheritance. Extend the default CodeIgniter controller with your own and put an authentication check in the constructor (check the session for a logged in flag or something and if not logged in then redirect to login page). Then, all controllers that require authentication will need to extend your new parent controller. That's it.
Head on over to the CodeIgniter forums and search for some different ways to extend the controller. Here is one http://codeigniter.com/forums/viewthread/89768/#452890
May be you can use CL_AUTH library for CI. I've used it and it works good. You can find it here http://www.jasonashdown.co.uk/cl_auth_doc/
I was looking into the same thing recently, and I found a CodeIgniter fork called Kohana that includes a nice authentication module. If you are set on CI, maybe adapting Kohana's auth module backwards to CI would save you some time? If you have just started out on your project and PHP5 is OK to use, consider switching over; they are very similar frameworks.
Visit GitHub and search for Codeigniter Auth or Authentication, or check the CodeIgniter Wiki, you'll find many libraries with different features.. explore them and choose the one you need! But be careful, many are for CI 2, and you have to ucfirst the classes to use with CI 3, otherwise they don't work at all.
Use flexi auth a modified version of the popular Ion Auth library. It's more advanced and do all the job out-of-the-box.
flexi auth is a free open source user authentication/login library for use with the CodeIgniter 2.0+ framework.
I know it's too late but I hope someone else will find it helpful. Cheers!

CodeIgniter questions: native PHP sessions, code flow, layout issues?

I am just getting started with CodeIgniter, and I am trying to hash out my regular modules/functions to get them working properly within the MVC framework. I have a few specific questions for anyone who has a strong CodeIgniter background:
SESSIONS
The CodeIgniter session stores session data on the client side in a cookie, which just isn't going to work for me. I know there are a few replacements for it, or I could build my own library/helper; but I just don't see any benefit over just using $_SESSION.
If I just use $_SESSION, will I have any problems with the rest of the framework? Does any other part of the framework depend on using the CodeIgniter session?
I feel a bit weird about stepping outside the framework for something so basic, but I am pretty comfortable with plain PHP. I am basically just looking to use CodeIgniter for MVC, and to enforce a more modular aspect for my projects.
CODE FLOW & CONFIG
I have a few config items that need to be done before almost anything else.
For example, say I have a constant APP_LIVE, which is set true/false based on the name of the current server. This has to happen really early as paths, error reporting, the CodeIgniter system, and application folders, etc. will be set based on it.
The problem is that the system_folder, and application_folder (which will be set based on which server the code is running on) are set first thing in the index.php file, before any of the configs have loaded.
Also, I have a functions that check for things in the URL, and may redirect before the page ever loads. For example, some pages need to enfore the presence of www. in the URL (for SEO), track affiliates, visitor sources, marketing flags, etc.
Where is the best place to put things like this that have to happen really early? I know there is a config file, an autoload file, a constants file, etc., but those are too late for some items. Is it a bad practice to simply put these things into the top of the main index.php file, or to make an include there to a global config file? Again, I feel like I am stepping outside the framework, and wonder if I'm just doing that because I don't have a solid understanding of it yet?
LAYOUT / HEADER FOOTER
Like most people, I have a top header, navigation, footer, etc. I am used to just having them in files, which are included into my page template. I believe I can do that the same way by just making them views and including them into my main page view. Is that the best way to go? Some of them need a bit of data; like what page they are on for the navigation, etc. What's the best way to handle navigation, shared header/footer, etc.?
The newly released CI 1.7 handles sessions in the database (if you're using one).
However, CI is designed to be loosely coupled, so you shouldn't notice any major issues if you decide to use $_SESSION instead.
For your header / footer / navigation, you could create (for example) headerview.php, footerview.php, and contentview.php, and pass data to your views by doing something like this in the controller:
$data['title'] = 'about us';
$data['content'] = 'hello world!';
$this->load->view('headerview', $data);
$this->load->view('contentview', $data);
$this->load->view('footerview');
Basically, you can treat these views exactly like includes, but with the added benefit that you can change the variables within. I would steer clear of calling other views from within views, but that might just be me.
I've made additions to index.php myself once or twice, to set initial values and such, and have never had a problem with it.
Congratulations on your choice of framework; I'm sure you won't be disappointed. ;)
You can either have multiple load->view lines in every controller but I personally find it coupled. I strongly suggest that you take a look at hooks in CodeIgniter where you can define functions that would be automatically run after each controller/method (a fine example of AOP).
Actually the $_SESSION array seems to get unset so you can't use the native PHP sessions (at least on 1.7). However in CodeIgniter wiki there's a session class that uses the native php sessions - you can use it the same way as the other, but it stores only session_id in the cookie. Here it is:
http://codeigniter.com/wiki/Native_session/
#lacho I created my own auth library on $_SESSION. and it works fine on 1.7.
I believe $_SESSION is much more secure since CI 'sessions' are cookies that are stored on the client side which are classified as 'user-passed-information' that can't be trusted.
You can try with native using your own session class
http://www.moreofless.co.uk/using-native-php-sessions-with-codeigniter/

Categories