How do I save an array into session in codeigniter? - php

I want to save an array in codeigniters' session helper but I keep getting
I want to save an array of arrays in a new session variable so that I can view that session in another controller if I need it or in another view.
my session is autoloaded in my config file.
this piece of code is in my view file.
$arr = array();
foreach($value->result as $val){}
if($val->somethinghappenedtrue){
$arr[] = array('data' => $thethingthathappened);
}
}
// since my session is autoloaded I don't need to initialize
//session if I'm not wrong $this->load->session etc...
$this->session->new_session_name($arr);
Fatal error: Call to undefined method CI_Session::new_session_name()

Let’s say a particular user logs into your site. Once authenticated, you could add their username and e-mail address to the session, making that data globally available to you without having to run a database query when you need it.
You can simply assign data to the $_SESSION array, as with any other variable. Or as a property of $this->session.
Alternatively, the old method of assigning it as “userdata” is also available. That however passing an array containing your new data to the set_userdata() method:
$this->session->set_userdata($array);
Your code should be
foreach($value->result as $val){}
if($val->somethinghappenedtrue){
$arr[] = array('data' => $thethingthathappened);
}
}
// since my session is autoloaded I don't need to initialize
//session if I'm not wrong $this->load->session etc...
$this->session->set_userdata($arr);
If you want to add userdata one value at a time, set_userdata() also supports this syntax:
$this->session->set_userdata('some_name', 'some_value');
If you want to verify that a session value exists, simply check with isset():
// returns FALSE if the 'some_name' item doesn't exist or is NULL,
// TRUE otherwise:
isset($_SESSION['some_name'])

Related

when i use get_userdata for session it gives Array ( [__ci_last_regenerate] => 1561454057 ) but when i use userdata it gives empty

I want to get the the user id of the current session in another after redirecting but it shows empty value. I'm using php 7.1.23 and ci 3.1.10.
$this->session->set_userdata('user_id',$user_id);
return redirect('Admin/Admin_dashboard');
$user_id = $this->session->get_userdata('user_id');
print_r($user_id); exit;
Try This --
$this->session->set_userdata('user_id',$user_id);
return redirect('Admin/Admin_dashboard');
$user_id = $this->session->userdata('user_id');
print_r($user_id);
exit;
You have use this $this->session->userdata('user_id');
The Session method get_userdata() does not accept an argument so I'm kind of surprised that your use does not throw an error. i.e.
$this->session->get_userdata('user_id'); //should throw an error`
$this->session->get_userdata() returns the whole $_SESSION array.
$this->session->userdata($key) returns $_SESSION[$key] if the key exists, or NULL if it does not.
The userdata() method exists only for backward compatibility. The recommended way to get a single item from session is to use this syntax.
$user_id = $this->session->user_id;
The above will set $user_id to $_SESSION ['user_id'] if the key 'user_id' exists, or NULL if it does not. It will also return an empty array if $_SESSION does not exist which is an indication that session has not been started. However, because you see __ci_last_regenerate we know that session is running.
The other possible reason for the empty array could be that you do not have session configured correctly which could result in session data not being stored and/or retrieved.

Sessions in Yii

Here I go what am doing is I am using
Yii::app()->SESSION['userid']
with no
Yii::app()->session->open();
at login
Yii::app()->session->destroy();
at logout
I wanna know if dont do the open and destroy session is it worthy . Does Yii do it internally.
One more strange thing I dont know whats happening. In the same browser for a session I can login for multiple users .. this should not happen so.Is it that i am not using the open and destroy session methods .
public function actionLogout()
{
Yii::app()->user->logout();
Yii::app()->session->clear();
$this->redirect(Yii::app()->controller->module->returnLogoutUrl);
}
Please let me know how do i figure this out
For creating yii session
Yii::app()->session['userid'] = "value";
You can get value like this
$sleep = Yii::app()->session['userid'];
And unset session like
unset(Yii::app()->session['userid']); # Remove the session
In case of user signs out , you have to remove all the session.
Yii::app()->session->clear();
After this, you need to remove actual data from server
Yii::app()->session->destroy();
Don't clear session, only logout:
Yii::app()->user->logout(false);
In YII, the session is handled by 'CHttpSession' class - http://www.yiiframework.com/doc/api/1.1/CHttpSession
Should you use the method 'open()' Yii::app()->session->open(); depends on your configuration. If in the main.php, you have set the
'session' => array (
'autoStart' => true,
), then the Session will be started automatically by YII itself.
You can refer the source code for the method 'init()' here - https://github.com/yiisoft/yii/blob/1.1.16/framework/web/CHttpSession.php#L83
Regarding your question about using the methods 'close()' or 'destroy()', the method 'close()' only unsets the keys of Session but 'destroy' removes the whole session data
Once you craeted session it will allow you in same browser multiple time, i mean for same url it will allow you to login, you can just do it rename your session variable with different name and check that particuller variable to login with that.
Session is a Web application component that can be accessed via Yii::$app->session.
To start the session, call open(); To complete and send out session data, call close(); To destroy the session, call destroy().
Session can be used like an array to set and get session data. For example,
$session = new Session;
$session->open();
$value1 = $session['name1']; // get session variable 'name1'
$value2 = $session['name2']; // get session variable 'name2'
foreach ($session as $name => $value) // traverse all session variables
$session['name3'] = $value3; // set session variable 'name3'

How to store array in CodeIgniter sessions?

I am calling a controller with method setActiveId and store 1 array in session and display after storing by using var_dump($this->session->all_userdata()) it shows perfectly but in same controller when I print the session in other method say checkinkingPermission then the array in session is empty.
Now I repeat all steps with one additional step.
I did store array in session like before and after storing I store one dummy variable in session like this,
$this->session->set_userdata('dummy','tesing');
and again print using var_dump($this->session->all_userdata()) it display all session with array and last dummy variable and when check in checkinkingPermission then array in session and dummy variable is shown perfectly (it solves my problem but its rough solution).
I want to know did anything miss or what problem is there that array not save in first scenario (also array is not greater then 4Kb (CI Session limit)).
Update
Method from model named connections_model
public function setActiveFriend($id) {
$this->load->model('friend_model');
$this->session->set_userdata('AF',$id);
if($id==$this->session->userdata('userid'))
{
$this->session->set_userdata('MEOWN',1);
}
else
{
$this->session->set_userdata('MEOWN',0);
}
$this->friend_model->setFP($id); // Calls Here a method that is defined in another model
}
Another method that defined in friend_model
public function setFriendPermissions($id) {
$this->session->set_userdata('CFP',array());
$this->db->where('user_id',$id);
$locs = $this->db->get('friend_p')->result_array();
if(is_array($locs))
{
foreach($locs as $loc)
{
array_push($this->session->userdata['CP'],$loc['perm_id']);
}
}
$this->session->set_userdata('dummy','tesing'); // Important Line
}
In above method I set values in session array if I want to see session values in same method then its set and viewed but the array is empty if I print session in any method of connections_model file.
Important
If I wrote this line $this->session->set_userdata('dummy','tesing'); then session array save and viewd in all methods and if I don't write that line session array is empty.
You're not accessing the session data properly:
$this->session->userdata['CURRENTFPERMISSIONS']
That's what you have. Keep in mind that $this->session->userdata is a function, not an array, that said, try this
array_push($this->session->userdata('CURRENTFPERMISSIONS'),$locpermission['perm_id']);
Please see the documentation on session management
I don't recommend using all cap keys for your arrays, as that convention is supposed to be used for constants.
In addition to the above, try changing this:
if(is_array($locpermissions))
{
foreach($locpermissions as $locpermission)
{
array_push($this->session->userdata['CURRENTFPERMISSIONS'],$locpermission['perm_id']);
}
}
to this
if(is_array($locpermissions))
{
$tmpArr = $this->session->userdata('CURRENTPERMISSIONS');
foreach($locpermissions as $locpermission)
{
array_push($tmpArr,$locpermission['perm_id']);
}
$this->session->userdata('CURRENTPERMISSIONS',$tmpArr);
}
Although, the more I look at your code, the more I don't understand why you are going ahead and setting up a blank array in the session structure if it only ever gets populated inside a conditional. May want to re-factor that a bit

Codeigniter Session->userdata is null

My project has several views which draw values out of the session->userdata array.
the whole project works flawlessly on my development machine, but when I copied the project up to a server, I find that $this->session->userdata is null.
This is the code which inserts some values into the session->userdata array:
It is called in the Controller.
$sessionArray = array(
'web_id' => $id,
'paperId' => $paperId,
'prelimId' => $prelimId,
'intakeId' => $intakeId,
'finalId' => $finalId,
);
$this->session->set_userdata($sessionArray);
In the view file I call
var_dump($this->session->userdata);
The value returned is null. As I mentioned before, the array is NOT null on my development computer (running WAMP). Does anyone know why?
In order to retrieve all session data as an ASSOC array, you could use the all_userdata() method. (Take a look at CodeIgniter user guide),
You can write that within your Controller and send the returned value to the view, as follows:
$data['userdata'] = $this->session->all_userdata();
$this->load->view('your/view.php', $data); // use $userdata in the view
Note: Using the session library directly inside the views may cause unexpected problems. Try managing your sessions in the Controller instead of the View.
Sorry for posting here in answer block first of all.......... Where you are assigning those values to $sessionArray. What i mean is in model or controller or in view file.
Are you calling var_dump($this->session->userdata) in view file.
Why don't you call that in controller and pass that as an array to view file via controller.
try like this in controller i will get user details in $login array from database for suppose when i submit username and password.
I will send those details to session array like this in model file
$this->session->set_userdata('logged_in_user', $login);
after that in controller if i want use user name from session array i will use like below.
$logged_in = $this->session->userdata("logged_in_user");
$model=array();
$model['logged_in_user']=$logged_in[0];
Once after i assigned to $model array i like to use that in view file so i will pass that $model array to view file from controller like this
$this->load->view('view_file_path',$model);
You can use that array in view file how ever you want from passed array.

store posted variables from a form long time

I have a form which is passing a number array like (56,78,98). I have stored that array in a variable called $array.
eg:
if(isset($_POST['submit']))
{
$checkbox_values=$_POST['checkbox_values];
$array= implode(',',$checkbox_values);
}
$_POST['checkbox_values] is values of check boxes from a form.
I need to retrieve value of $array after the if(isset($_POST['submit'])) condition. I am using zend frame work. How can I use $array after if condition? or how can I use session or cookie in zend?
Thanks!!!
you could assign the array directly to the session using Zend_Session_Namespace:
//you can initialize the session namespace almost anywhere.
$session = new Zend_Session_Namespace('form')
if(isset($_POST['submit'])) {
$checkbox_values=$_POST['checkbox_values'];
//will assign values to session namespace 'form' as key 'checkbox_values' as an array
//session namespace will also accept objects and scalar values.
$session->checkbox_values = implode(',', $checkbox_values);
//$array= implode(',',$checkbox_values);
}
you can use the array any way you choose. You can pass it to the view...
$this->view->checkboxValues = $session->checkbox_values;
or you can pass it to your favorite model, what ever you need to do you can do. the session will remain until you unset it or overwrite it.
Good Luck.
you are missing a single quote
$checkbox_values = $_POST['checkbox_values'];
otherwise everything looks fine.

Categories