How to store array in CodeIgniter sessions? - php

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

Related

Get Session data in store function

Is it right to get Session data in a store function and store them into db?
public function store(){
...
$idgroup = Session::get('invitation_userid')];
...
}
Or need a store function always a Request Object?
public function store(Request $request){
...
$idgroup = $request('idgroup');
...
}
In both functions is of course a validation part for the input data.
Both approaches are fine, but you should use them appropriately to your use case, I prefer to use the Request data. The main difference is that if u store that inside the Session it will be available application wide, while if u send inside Request it will be available inside the method only
This depends entirely on the context of what your controller is actually named, how this data is being used and why you are not using a database session driver in the first place if you want to do this.
You could simply use the database driver for the session:
https://laravel.com/docs/5.7/session#introduction
It also depends on what your controller is named if you strictly want to follow restful routes:
https://gist.github.com/alexpchin/09939db6f81d654af06b
To answer the second question you don't always need a Request object in your store action. Most of the time you won't even see a Request object because you are simply creating an entirely new resource.
The Global Session Helper
You may also use the global session PHP function to retrieve and store data in the session. When the session helper is called with a single, string argument, it will return the value of that session key. When the helper is called with an array of key / value pairs, those values will be stored in the session:
$value = session('key');

How do I save an array into session in codeigniter?

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'])

Is there a way of passing a multidimensional array into a session?

I've been trying with this issue all morning. When i load the function which sets the array directly, and remove the redirect, it works fine. All of the data in both levels of the array is there. When i add back in the redirect, the function redirects and the second level of the array is removed. Leaving just the first. So the Session is setting, but it's dropping the data from the session for some reason.
The Function Which controls the array and redirect
public function test(){
$i=$_GET['i'];
$this->construct_data();
redirect('view/name?i='$i);
}
public function construct_data(){
$i=$_GET['i'];
list($array1)=$this->array1($i);
list($array2)=$this->array2($i);
list($array3)=$this->array3($i);
list($array4)=$this->array4($i);
list($array5)=$this->array5($i);
list($array6)=$this->array6($i);
$container= array(
'array1'=>$array1,
'array2'=>$array2,
'array3'=>$array2,
'array4'=>$array4,
'array5'=>$array5
);
$this->session->set_userdata('construct',$container);
}
The view
$data = $this->session->userdata('construct');
var_dump($data);
The var_dump in the view returns all of the first level of container, array 1 through 5. But it doesn't contain any of the data inside of the functions that are called. it returns $data['array1'].
Now if i were to put the var_dump inside the test function instead of redirect, the data is returned as it should be, $data['array1']['array1item'].
Let me know if this was unclear. Also the names of variables and functions were changed to maintain anonymity.
Instead of adding array directly to session, first convert it into json by using json_encode() function. On retrieving you have decode it by using json_decode() function.
Add To session
$this->session->set_userdata('construct',json_encode($container));
Reading From Session
$data = $this->session->userdata('construct');
var_dump(json_decode($data,true));
Okay, the actual problem was size. I was making it too big and as a result it couldn't pass it outside of the class.

PHP - Run function after while loop ends

This may not be the best solution to my problem, but I'm interested to know anyway.
Is it possible to defer a function or piece of code till after a while loop ends? I assumed this happened anyway if it was placed below, but that doesn't seem to be the case.
What I'm trying to accomplish is inside the while loop some session data is being saved (if it does not exist, which is the condition). When the loop finally ends, since the session data is set, the code below which relies on the session data can be executed.
This is in a CodeIgniter 3.0 system, so it is using the session driver:
// Uses a helper function session_isset (see below) to check if the session data is set, and if at least one of the supplied data variables is null then try to set it
while(!session_isset(array('instance_id','instance_prefix'))) {
$this->session->set_userdata('instance_id', $instance->instance_id);
$this->session->set_userdata('instance_prefix', $instance->instance_prefix);
}
// The get_managers() function, which ultimately calls a model function, relies on the set session data to get a table prefix which is prepended to all relevant database queries
// This should ideally only be allowed to run once the session data has been confirmed as set
if($manager = $this->manager->get_managers(array($manager_id))[0]) {
$manager->instance_id = $instance->instance_id;
$manager->instance_prefix = $instance->instance_prefix;
echo json_encode($manager);
}
function session_isset($data) {
$ci =& get_instance();
foreach ($data as $value) {
if(is_null($ci->session->userdata($value))) return FALSE;
}
return TRUE;
}
So just to reiterate, is there a way to defer code until a while loop has ended, similar to a callback?
Also, is there perhaps a better way to ensure session data is set before running functions that depend on it?

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