Changes to $_SESSION without page reload - php

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);
}

Related

Cookie array with strings returns false

I'm trying to add the current page's URL to a cookie called '$visitedPages'. For reference, the Wordpress function 'get_permalink()' returns the URL.
In the below, the var_dump returns 'false'. Whereas if I replace 'get_permalink()' on line 2 with 'get_the_ID()', which returns the integer page IDs, this all works just fine.
I tried stripping special characters from the url, but it still returns 'false', so I suspect this problem is something to do with decoding strings from the cookie.
// define the new value to add to the cookie
$currentPage = get_the_permalink(get_the_ID());
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(isset($_COOKIE['visitedPages'])) {
$visitedPagesSerialised = $_COOKIE['visitedPages'];
$visitedPages = unserialize($visitedPagesSerialised)
var_dump($visitedPages);
} else {
$visitedPages = array();
}
// add the current page id to the array and serialize
$visitedPages[] = $currentPage;
$newCookieSerialized = serialize($visitedPages);
// save the cookie for 30 days
setcookie('visitedPages', $newCookieSerialized, time() + (86400 * 30), "/");
?>
Try getting the ID, and adding it in to the permalink function. I'm assuming when you say you used get_the_ID() it means you are replacing permalink function with get ID function. Try using them in tandem.
$page_ID = get_the_ID();
$currentPage = get_the_permalink($page_ID);
I needed to remove escaped quotes from the cookie with stripslashes() before the json_decode. Why json_decode doesn't do this itself, I have no idea.
Here is the working code. Note: it is better to use exactly the same code but with json_encode() and json_decode() instead of serialize() and unserialize() so I've changed that too, but the principle is the same.
// define the new value to add to the cookie
$currentPage = get_the_permalink(get_the_ID());
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(isset($_COOKIE['visitedPages'])) {
$visitedPagesSerialised = stripslashes($_COOKIE['visitedPages']);
$visitedPages = json_decode($visitedPagesSerialised)
var_dump($visitedPages);
} else {
$visitedPages = array();
}
// add the current page id to the array and serialize
$visitedPages[] = $currentPage;
$newCookieSerialized = json_encode($visitedPages);
// save the cookie for 30 days
setcookie('visitedPages', $newCookieSerialized, time() + (86400 * 30), "/");

Why is my session not holding its data?

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();

Partially delete/destroy $_SESSION data? PHP

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.

PHP variable name conflict with session variables

I have the following segment of code that someone else has written, and that I'm trying to fix:
function calc() {
require_once("db.php");
connect();
$a = split("#", $_SESSION['freight']);
$loc = $a[0];
$r = mysql_query("SELECT `price`, `gst` FROM `freight` WHERE `location`='$loc'");
$arr = mysql_fetch_array($r);
$_SESSION['freight'] = $loc."#".$arr['price'];
return $arr['price'];
}
function ajaxFunction () {
$_SESSION['freight'] = $_GET['loc'];
$freight = calc();
echo number_format($freight, 2);
return;
}
It ain't pretty, I am just trying to fix it.
Now I have noticed the bug seems to stem from the fact $freight = calc(). After that line, $freight will equal say $10 (the $arr['price'] value). BUT the $_SESSION['freight'] will also equal $10, and just $10, as if it was the same variable as $freight. What ever I set $freight to, the $_SESSION['freight'] also becomes.
If I change $freight in the ajax function to $freight2 it doesn't alter the session variable. Is this something major that I don't know about PHP? That variable names share the same namespace as session variables?
The question overall is:
Does changing $a alter $_SESSION['a'] in anyway? Because it really seems like it does.
It looks like your register globals is set to on in your php.ini file. You need to turn that off. If it's on, your $_SESSION, $_GET, $_POST elements can be referred to as the variable names.
e.g. $_SESSION['item'] is the same as $item
More info here: http://us2.php.net/manual/en/ini.core.php#ini.register-globals
Also, register globals is now deprecated, which also means that if this is indeed the issue, you were using an older version of PHP, and may want to consider upgrading.
As far as I can tell...
your $_SESSION variable should not be a session variable at all as it always equals $_SESSION['freight'] = $loc."#".$arr['price'];
I actually do not understand the use of the session so this is whow i would have approach it
function calc($loc)
{
require_once("db.php");
connect();
$r = mysql_query("SELECT `price`, `gst` FROM `freight` WHERE `location`='$loc'");
$arr = mysql_fetch_array($r);
$_SESSION['freight'] = $loc."#".$arr['price'];
return $arr['price'];
}
function ajaxFunction ()
{
$a = split("#", $_GET['loc']);
$freight = calc($a[0]);
echo number_format($freight, 2);
return;
}
You only need the location so that you can run your queries. So just set the session once with the new data from the database.
Hope that helps
I always use different notation for session variables. For example $_SESSION['_uid'] versus a regular $uid variable.

php session_start default value?

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

Categories