How to retrieve the session values in Yii 2 - php

I am facing the problem with Yii 2 session when I add the products to the cart session and fetch session cart values.
session_start();
print_r($_SESSION);
exit;
I got this line.
Array ( [__flash] => Array ( ) [__id] => 65 )
Also while trying Yii 2 way:
$session = Yii::$app->session;
print_r($session);
exit;
I am getting this value:
yii\web\Session Object (
[flashParam] => __flash
[handler] => [_cookieParams:yii\web\Session:private] => Array ( [httponly] => 1 )
[_hasSessionId:yii\web\Session:private] => 1
[_events:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] =>
How to get the session data with keys and values in Yii 2?

Hi Sai you can set or retrieve the session value in yii2 easily by using the following steps
1) To set session value on var 'userVariable'
Yii::$app->session->set('userVariable','1234');
2) For getting the session value of var 'userVariable'
$userVariable = Yii::$app->session->get('userVariable');

you can get session by using $session = Yii::$app->session; hope it will help you :)

First, you need to open session
Yii::$app->session->open();
And you can get all session using $_SESSION
var_dump($_SESSION);exit;
May be useful!

You don't need to start session IF you are using YII2 framework.
Follow these step:
1. $session = Yii::$app->session;
2. $session->set('key', 'value');
3. $session->get('key');
Otherwise directly set value
$session['key']=>'value'

you can get session ID with
Yii::$app->user->id
//OR
Yii::$app->user->identity->id
and you can set new session with
$session = Yii::$app->session;
$session->set('new-name-session', '1234');
check all session with
var_dump($_SESSION);exit;

You need to process Yii::$app->session object in for/foreach loop, like so:
foreach (Yii::$app->session as $key => $value) {
var_dump($value);
}

Related

How to assign value if not increment? laravel

I want to assign a value if not exist else increment the value. Below is the one line code that I'm trying to achieve.
session()->put(['validation_count' => session('validation_count')++ ?? 1]);
But I end up this error below.
Can't use function return value in write context
Someone knows the perfect one line solution?
$validationCount = session('validation_count');
session()->put(['validation_count' => ($validationCount ? $validationCount++ : 1]);
Update for comment:
I recommend with variable usage but if you want to one line:
session ()->put ( ['validation_count' => ( session ( 'validation_count' ) ? session ( 'validation_count' ) + 1 : 1 )] );
session ()->save ();
In one line, you can do like so:
session()->put(['validation_count' => (session('validation_count') ? session('validation_count') + 1 : 1)]);

Laravel - Array in session not destroying using session forget method

In my Laravel project I am storing array in to session. I tried to delete the whole array from session using session forget method, but it is not working. I can access sessions after session forget. Any help would be appreciated thank you.
Storing data in to session
$item = [
'name' => 'Test',
'normalIdSession' => 'Normal Data',
'guestsSession' => '1',
'amountSession' => '200'
];
$request->session()->put('item', $item);
Deleting session
if(session()->has('item'))
{
$name = session()->get('item.name');
$normalIdSession = session()->get('item.normalIdSession');
$guestsSession = session()->get('item.guestsSession');
$amountSession = session()->get('item.amountSession');
// Here data storing in to database and deleting sessions.
session()->forget('item');
dd($name); // Here I can access session data.
}

I Need to add items to array, not replace them

I have a little script system. It replaces the array but I need it to add to the array. This is what I have:
$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item1'); // Item added to cart
If after this I submit:
$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item2'); // Item added to cart
It will contain item2 in array not item1 and item2.
How can I get it to do this?
So I changed up my code a bit and not when I push for example the code below twice it will overwrite the item. How can I make it add another one instead?
array_push($_SESSION['cart']['itemName'] = 13.99);
It seems that you are recreating the array on the second set of code meaning that you will delete everything already in the array. Did you try just array_push without the $_SESSION['cart']=array(); for the second set of code? If not try getting rid of that first line and see if it works.
Use this syntax to append:
$_SESSION['cart'][] = 'item1';
$_SESSION['cart'][] = 'item2';
Edit:
// declare only if needed
if (!array_key_exists('cart', $_SESSION)) $_SESSION['cart'] = array();
// when adding an item at any future time once $_SESSION['cart'] exists:
$_SESSION['cart'][] = array(
'itemName' => 'my item',
'price' => 13.99
);
By calling this line every time :
$_SESSION['cart']=array();
You are cleaning out your cart session. If you wrap that in an if statement as well to check whether the array has already been instantiated, then you won't clean it out each time and you should be able to add to it as expected:
if (!isset($_SESSION['cart'])) {
$_SESSION['cart']=array();
}
You are emptying your array before you add to it you declare $_SESSION['cart'] to equal a new empty array
U declared 2 times $_SESSION['cart']. Remove second declare and you should be good to go.
EDIT :
U don't use correct syntax for array_push.
PHP.net : array_push()
If i understood correctly - the index of key (numeric since array_push) bothers you.
U can bypass by using this code :
$_SESSION['cart'] = array();
$_SESSION['cart']['itemName'] = 12.50;
$_SESSION['cart'] = $_SESSION['cart'] + array("blabla" => 13.99);
print "<pre>";
print_r($_SESSION);
print "</pre>";
Result :
Array
(
[cart] => Array
(
[itemName] => 12.5
[blabla] => 13.99
)
)
LAST EDIT : (!?!)
function set_item_price($itemName, $itemPrice)
{
if(!isset($_SESSION['cart'][$itemName]['itemPrice']))
$_SESSION['cart'][$itemName]['itemPrice'] = $itemPrice;
else
echo "Item Already exists \n <br>";
}
function add_to_cart($itemName, $quantity)
{
if(!isset($_SESSION['cart'][$itemName]['quantity']))
$_SESSION['cart'][$itemName]['quantity'] = $quantity;
else
$_SESSION['cart'][$itemName]['quantity'] += $quantity;
}
// Adding item1 - price 12.50
set_item_price("item1", 12.50);
// Adding item1 - quantity - 2 & 3
// OutPut will be 5
add_to_cart("item1", 2);
add_to_cart("item1", 3);
// Adding item3 - price 15.70
set_item_price("item3", 15.70);
// Adding item1 - quantity - 5
add_to_cart("item3", 5);
print "<pre>";
print_r($_SESSION);
print "</pre>";
?>
RESULT :
Array
(
[cart] => Array
(
[item1] => Array
(
[itemPrice] => 12.5
[quantity] => 5
)
[item3] => Array
(
[itemPrice] => 15.7
[quantity] => 5
)
)
)
Otherwise check on this thread :
Stackoverflow : how-to-push-both-value-and-key-into-array-php

Updating previous Session Array Laravel

I have an issue on how can I update my Previous array ?
What currently happening to my code is its just adding new session array instead of updating the declared key here's my code:
foreach ($items_updated as $key => $added)
{
if ($id == $added['item_id'])
{
$newquantity = $added['item_quantity'] - 1;
$update = array(
'item_id' => $items['item_id'],
'item_quantity' => $newquantity,
);
}
}
Session::push('items', $updated);
$items = Session::get('items', []);
foreach ($items as &$item) {
if ($item['item_id'] == $id) {
$item['item_quantity']--;
}
}
Session::set('items', $items);
If you have nested arrays inside your session array. You can use the following way to update the session: $session()->put('user.age',$age);
Example
Supppose you have following array structure inside your session
$user = [
"name" => "Joe",
"age" => 23
]
session()->put('user',$user);
//updating the age in session
session()->put('user.age',49);
if your session array is n-arrays deep then use the dot (.) followed by key names to reach to the nth value or array, like session->put('user.comments.likes',$likes)
I guess this will work for you if you are on laravel 5.0. But also note, that I haven't tested it on laravel 4.x, however, I expect the same result anyway:
//get the array of items (you will want to update) from the session variable
$old_items = \Session::get('items');
//create a new array item with the index or key of the item
//you will want to update, and make the changes you want to
//make on the old item array index.
//In this case I referred to the index or key as quantity to be
//a bit explicit
$new_item[$quantity] = $old_items[$quantity] - 1;
//merge the new array with the old one to make the necessary update
\Session::put('items',array_merge($old_items,$new_item));
You can use Session::forget('key'); to remove the previous array in session.
And use Session::push to add new items to Session.

Codeigniter says session userdata blank, but exists in db

Whenever i try check for a value in my userdata column of my session it thinks it's blank, when it's actually in the ci_sessions table serialised.
here's the db content unserialised:
array (
'user_data' => '',
'edit' =>
array (
'image_id' => 'HF',
'session_id' => '783c15b057bcd9c19d3fd82f367ee55d',
),
)
here's how im checking for the userdata in my view (note sessions are autoloaded)
<?php if ($this->session->userdata('edit')) : ?>
enter code here
and here's how i set the session userdata:
$values = array(
'image_id' => implode(",",$uploaded_image_ids),
'session_id' => $this->session->userdata('session_id')
);
$this->session->set_userdata('edit', $values);
Can anyone see the problem? (whole controller here http://pastebin.com/aXeRn1VN)
Also heres my config.php http://pastebin.com/A31nrC1b
View variables are separate from other variables in CI. I think (am still a bit of a CI newbie) that $this->session is not available in Views. This CI forum post discusses a couple of possible solutions to the problem http://codeigniter.com/forums/viewthread/100587/#508098 - one is to pass the value of 'userdata' from the session into the $data array you pass to the view - which seems the best solution.
You can use like this
<?php $edit = $this->session->userdata('edit'): if (!empty($edit)) : ?>

Categories