I've never run into this before but for some reason, when I am using AJAX to set a session variable, the session will not hold them.
Here is what I have:
session_start();
if(isset($_POST['selected'])){
$_SESSION['user']['theme'] = array ('selected' => true);
} // This should be now set with the value and it is for a time, but unsets
if(isset($_POST['theme'])){
$_SESSION['user']['theme'] = array('name' => $_POST['theme']);
} // So should this
What I am seeing when I do a print_r under both if constructs is only the $_SESSION['user']['theme']['name'] var and the other is not set. If I do a print_r just under the selected var, I can see it just fine. Somewhere, the key and value are disappearing for selected.
Why is this happening? I'm expecting to see both name and selected.
Like i said in my comment, you're overriding the array :)
session_start();
//changed it to unset if not in $_POST
$_SESSION['user']['theme']['selected'] = isset($_POST['selected']);
if(isset($_POST['theme'])){
$_SESSION['user']['theme']['name'] = $_POST['theme'];
} // and unset it too
else {
$_SESSION['user']['theme']['name']= "";
}
You need to start the session first
session_start();
if(isset($_POST['selected'])){
$_SESSION['user']['theme'] = array ('selected' => true);
}
And also check whether the $_POST values are not empty.And you need to unset the name in session then assign it like
if(isset($_POST['theme'])){
unset($_SESSION['user']['theme']['name']);
$_SESSION['user']['theme'] = array('name' => $_POST['theme']);
}
At the start of any page that sessions variables are accessed in any way, the first command must be a call to session_start();
Related
I have this small script that runs after a user posts.
I have a $_SESSION['con29'][value] that I populate with data from the post.
This code should either add or remove an array element.
It adds an element fine, but I can't work out why it won't unset the $_SESSION array
if (isset($_POST['sub_search_content_id']))
{
$row_id_1 = $_POST['sub_search_content_id'];
$_SESSION['con29'][$row_id_1] = $_POST['sub_search_content_id'];
}
if (isset($_POST['sub_search_content_id_remove']))
{
$ss_id = $_POST['sub_search_content_id_remove'];
unset($_SESSION['con29'][$ss_id]);
}
Use !empty instead isset
because isset only will check variable is created or not
but !empty will check variable is empty or not too.
and if you don't have another session variables so you may try
session_unset();or session_destroy();
and you can also use
session_register($value);
and
session_unregister($value);
for this
Hope this helps
I have two $_SESSION variables declared as array in index.php, say:
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
I make a AJAX call from index.php to result.php, where values of session variables are changed
to, say:
$_SESSION['a'] = array(2,3,1,4);
$_SESSION['b'] = array(5,6);
What I do is, I remove the first element from both the arrays and append it back to first array, $_SESSION['a'].
On successful AJAX call, I want to print the first elements of both the variables in index.php. Is it possible?
Yes, on a successful ajax call, you can do that.
This is pretty straight forward.
In your results.php you simply returned the new data with a bit of JSON.
result.php:
//set the session vars to whatever here....
//now, return them. In the example, I shall assign your session vars to temp vars.
$sessA=$_SESSION['a'];
$sessb=$_SESSION['b'];
echo json_encode(array('a'=>$sessA,'b'=>$sessb));
And now in your AJAX (assuming you're using jQuery):
$.getJSON('results.php', function(data){
alert(data.a);
alert(data.b);
});
And there you have it.
EDIT:
In your index.php, you say you set the session vars to the original value. But in your comments, you say you want to use the new vars in index.php. This won't be possible if you are setting them to the original value in index.php on every request. What you should do is check if they're already set first, and then do what needs to be done. Like this:
instead of:
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
Do this:
if ( isset($_SESSION['a']) === false && isset($_SESSION['b']) === false )
{
# - The vars are not already set...so it's okay to set them to its original value.
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
}
I am looking for a way to delete only certain amounts of SESSION data that is stored whilst preserving the session data associated with the user being logged on.
At the moment I am doing this by individual unset statements to the SESSION variables I want to delete.
However I was hoping there may be a more clever way to just delete a whole section of the SESSION array whilst preserving specific variables
e.g.
$_SESSION['username'];
$_SESSION['user_id'];
$_SESSION['ttl'];
The use case for this process would be:
User Logs In --> User performs task --> Once task is complete delete session data associated with task --> User is still logged in!
I had considered perhaps using a table in my Database monitoring logins, what are your opinions on that?
Thanks for your time!
There is no way to delete "whole section of the SESSION array whilst preserving specific variables".Instead of that you can use two dimensional array for a task and delete that array.
$_SESSION["task1"]["username"] = "name"
$_SESSION["task1"]["pass"] = "pass"
$_SESSION["task2"]["name"] = "name";
when task1 complete delete like
unset($_SESSION["task1"]);
now $_SESSION["task2"] still exist.
Well you could store all this volatile data inside another key:
$_SESSION['volatile'] = array(
'one' => 'value'
);
If you dnt want to do that you could use array comparison functions like:
// specify what keys to keep
$_SESSION = array_intersect_key($_SESSION, array('keepme1', 'keepme2', 'etc'));
//specify what keys to remove
$_SESSION = array_diff_key($_SESSION, array('deleteme1', 'deleteme2', 'etc'));
As far as the DB you could do that but its not necessary to accomplish your objective, and unless there are moving parts you didnt list in your original question id say you probably dont need to do anything that complex right now.
Structure your session data in a hierarchy:
$_SESSION['loggedIn'] = TRUE;
// Temporary session data
$_SESSION['temporary'] = array(
'temp_var1' => 'foo',
'temp_var2' => 'bar',
// ...
'temp_var99' => 'baz'
);
echo $_SESSION['temporary']['temp_var2']; // bar
// Remove all temporary session data
unset($_SESSION['temporary']);
echo $_SESSION['loggedIn'] ? 'yes' : 'no'; // yes
I will have to disagree with #sathishkumar, the following method destroys partially session variables.
public static function destroyPartial($keys)
{
if (session_status() === \PHP_SESSION_NONE) {
session_start();
}
if (!is_array($keys)) {
$keys = [$keys];
}
foreach ($_SESSION as $k => $v) {
if (in_array($k, $keys, true)) {
unset($_SESSION[$k]);
}
}
$recoveringSession = $_SESSION;
session_destroy();
session_start();
$_SESSION = $recoveringSession;
}
In the php docs for the session_destroy function, we can read this:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
So, the "trick" is to call session_start AFTER session_destroy.
Hope this helps.
I am just trying to write a function in php that adds to the discount array but it doesn't seem to work at all.
function addToDiscountArray($item){
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Every time I refresh the page it acts like $_SESSION["discountCalculator"] hasn't been set up but I can't understand why. Whilst writing can I use the $_SESSION["discountCalculator"] in a foreach php loop in the normal way too?
Many thanks
The fact that every time $_SESSION['discountCalculator'] seems not to be set, could be because $_SESSION is not set (NULL). This case happens mostly when you did not executed session_start() at the beginning of you page.
Try adding session_start() at the beginning of the function.
function addToDiscountArray($item) {
if (!$_SESSION) { // $_SESSION is NULL if session is not started
session_start(); // we need to start the session to populate it
}
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Notice that this will not affect the function if the session is already started. It will only run ´session_start()` if the session is not started.
I have a question regarding a session variable.
I have session variable which needs to start at a default variable. Then I need to be able to pass a new one through $_GET and keep that updated. So that even if the user reloads the page, it does not go back to the default value. How might I go about doing this? Thanks!
With this snippet you'll have session variable assigning once:
if (!isset($_SESSION['magic'])) {
$_SESSION['magic'] = isset($_GET['magic']) ? $_GET['magic'] : 1;
}
Seems like something along these lines might work:
if(!isset($_SESSION['my_parm']))
{
$_SESSION['my_parm'] = 'DEFAULT';
}
if(isset($_GET['my_parm']))
{
$_SESSION['my_parm']=$my_parm;
}
Use
session_start();
$_SESSION
below is the link for session manual
http://www.php.net/manual/en/reserved.variables.session.php
If I understood well, this would be an outline of your method:
<?php
session_start();
if (isset($_GET['my_variable'])) {
$_SESSION['my_variable'] = $_GET['my_variable']; // force new value
}
if (!isset($_SESSION['my_variable'])) {
$_SESSION['my_variable'] = $default_value; // initialize
}
update_value($_SESSION['my_variable']);