Codeigniter Session Class userdata? - codeigniter-2

i have some question in Codeigniter session class:
whats different between these
$this->session->all_userdata();
$this->session->userdata
both of them return array of all user data in ci session (cooke).
and why this code is wrong:
$this->session->userdata();
but this one is correct:
$this->session->userdata
why?

for 1:
$this->session->all_userdata(); is method to get CI-session's data
$this->session->userdata is variable of CI-session's class, You shouldn't get session's data this way.
for 2:
$this->session->userdata(); is correct because this way You'll use setters-getters mechanism (read more here), $this->session->userdata is incorrect because You try to get data directly (read link above to get more info)

Related

Cakephp 2.0 can't get or read session view file?

I'm working to display or read session in view ctp file, but controller showing is session created and read session is also showing in the controller but can't display or read session in view ctp file?
controller function
var $components = array('Auth','Session','RequestHandler','Email');
$selectedlocation= $_POST['location'];
$this->Session->write('homepagelocation.selectlocation', $selectedlocation);
echo $this->Session->read('homepagelocation.selectlocation');
session reading method in ctp file
echo $this->Session->read('homepagelocation.selectlocation');
In order to access data from the controller in your view, you need to set the data to the view.
var $components = array('Auth','Session','RequestHandler','Email');
$selectedlocation= $_POST['location'];
$this->Session->write('homepagelocation.selectlocation', $selectedlocation);
$this->set('location', $this->Session->read('homepagelocation.selectlocation'));
I will ask however, why are you writing data to the session, reading from it and setting that to the view when you already have access to the data you need in $selectedlocation?
Ello, mate. I think you $_POST[] does not work this way into your controller, you should try:
$this->request->data['location']; //Cake 2.x
$this->data['location']; //Cake 1.3
Then you set up the session to the view:
$this->set('location', $this->Session->read('homepagelocation.selectlocation'));
Now you can print it on your view:
echo $location;
You can check here: http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
It is possible to use Session read method in view, please set Session as $helper element in Controller.

Real Dilemma when using Sessions, Cookies in Yii

I have set sessions for my properties/methods in WebUser like following
public function getRole(){
$user = $this->loadUser(Yii::app()->user->id);
$this->setState('roleId', $user->roles_id);
return $user->roles_id;
}
In the config, I have set autostart sessions to 'true', cookieMode to 'only'. I understand that when i 'setState', the cookie with the same name is also created along with the session variable. Currently I am calling these variables using Yii::app()->user->roleId;
My question is this:
a) To utilize from the cookies and/or the session variables already set, should i call them using Yii::app()->request->cookies['roleId']; or Yii::app()->session['roleId']?
b) Will calling Yii::app()->user->roleId get me the value if it is already set as Cookie or Session instead of running the whole method again?
I appreciate your support!
I would only use sessions for that. Cookies can be easily tampered with and a user could probably assign himself another role id. Session is somewhat safer.
Use your WebUsers getRole() for that, which caches it in the session like you have above. This is fine. Just put a check at the top, if there is a session var roleId instantly return it. If not, load the user and get it there like you already have.

Reading a session variable inside a behavior in cakephp 2

I have a behavior which enables segregation of user data based on the user id stored in the session. In CakePHP 1.3 you could do this:
App::import('Component', 'Session');
$session = new SessionComponent();
$session->read('Auth.User.id');
But in CakePHP 2, you can't instantiate a component like that in a behavior because the Component __construct requires the Controller's ComponentCollection as a parameter.
Is it possible to access a session variable inside a behavior in CakePHP 2? What's the best way to do it?
If you look at the SessionComponent code, you will see that it is only a wrapper for the CakeSession class.
So you can do the following:
App::uses('CakeSession', 'Model/Datasource');
$user_id = CakeSession::read('Auth.User.id');
In CakePHP 2.0 you can also simply call the Session-methods via the static CakeSession::method() without having to load anything... ;-)

flashdata not being stored between redirects when using Tank Auth

I'm using the latest version of Codeigniter and tank_auth 1.0.9 on a site I'm building.
When using set_flashdata() and flashdata() respectivly, nothing is being returned on redirect but if I set sess_use_database to FALSE in the config it works.
I've searched around and couldn't find an answer -- Has anyone else run into this issue and fixed it?
I was having the same issue and figured out the problem. If you're storing sessions in the database, it will not work.
Tank Auth runs this code from the main library ( $this->tank_auth->logout() ):
$this->delete_autologin();
// See http://codeigniter.com/forums/viewreply/662369/ as the reason for the next line
$this->ci->session->set_userdata(array('user_id' => '', 'username' => '', 'status' => ''));
$this->ci->session->sess_destroy();
Then it runs this code from the auth controller ( $this->_show_message() ):
$this->session->set_flashdata('message', $message);
redirect('/auth/');
The problem is that since sess_destroy() was run prior to setting the flashdata, there is no database row to add the flashdata to, so the flashdata never gets set.
At this point there are a few solutions:
Option 1:
Add $this->ci->session->sess_create(); immediately after $this->ci->session->sess_destroy(); in function logout() in application/libraries/Tank_auth.php
This works because you are creating a new blank session where flashdata can be stored. A potential con for this is that you are performing more operations on the database (delete+insert).
Option 2:
Comment out/delete $this->ci->session->sess_destroy(); in function logout() in application/libraries/Tank_auth.php
This works because the session is not destroyed, allowing CI to perform only an update query to add flashdata. This is probably better than option 1 unless you absolutely need to destroy the session.
Option 3:
Set $config['sess_use_database'] to FALSE.
This works because a session is automatically created when it is requested again, as opposed to how it works when you store sessions in the database. Potentially less secure.
In the end, it is up to you to decide which option is best for your application.
if tank_auth does any internal redirects then you may lose the flash data on that redirect request.
Exactly.
CodeIgniter documentation specifies here:
http://codeigniter.com/user_guide/libraries/sessions.html
=============================
Destroying a Session
To clear the current session:
$this->session->sess_destroy();
Note: This function should be the last one called,
and **even flash variables will no longer be available**.
If you only want some items destroyed and not all, use unset_userdata().
=============================
I've digged into the system/libraries/Session.php file and saving flashdata triggers the sess_write() method which only UPDATES the database as you said.
To me a better fix is checking to make sure the session exist before setting the flashdata in show_message().
function _show_message($message)
{
// Patch for show_message() after logout(). Make sure the session exist before set_flashdata().
if(!$this->session->sess_read())
{
$this->session->sess_create();
}
$this->session->set_flashdata('message', $message);
redirect('/auth/');
}

Codeigniter pre_system hook for DB driven dynamic controller selection - best approach?

Although I can tentatively see a solution to this, I was wondering if there may be a glaringly obvious simpler approach.
My aim is to use the first segment of a given URI to query the DB as to which controller should be run.
I assume I would have to reform the URI with the resultant controller name in segment 1, then allow the system to continue processing as normal (hence a pre_system hook).
Although not essential I would also like to hold a couple of other variables from the same DB request to be used later in the call stack, and assume this would have to be done using global variables?
Any better suggestions would be gladly received.
Thanks.
Should it be of use to anyone else, here is the code to acheive the desired result. This does however not take into account passing additional variables because I can live without them.
function set_controller()
{
include_once APPPATH.'config/database.php'; //Gather the DB connection settings
$link = mysql_connect($db[$active_group]['hostname'], $db[$active_group]['username'], $db[$active_group]['password']) or die('Could not connect to server.' ); //Connect to the DB server
mysql_select_db($db[$active_group]['database'], $link) or die('Could not select database.'); //Select the DB
$URI = explode('/',key($_GET)); //Break apart the URL variable
$query = 'SELECT * FROM theDomainTable WHERE domainName = "'.$URI[1].'"'; //Query the DB with the URI segment
if($results = mysql_fetch_array(mysql_query($query))){ //Only deal with controller requests that exist in the database
$URI[1] = $results['controllerName']; //Replace the controller segment
$_GET = array(implode('/',$URI)=>NULL); //Reconstruct and replace the GET variable
}
mysql_close($link); //Close the DB link
}
I wouldn't use global variables, Id prefer to store it in a library for retrieval later if possible. Global variables are kind of messy in the context of CI.
Although at pre_system Only the benchmark and hooks class have been loaded at this point. This means you're pretty-much stuck with global variables unless you can find a way to select the controller on pre_controller as all the base-classes are loaded and you can put the data somewhere more logical.

Resources