php session variable not updating a 2 dimensional array after initializing - php

I'm almost embarrassed to ask because it seems so simple, but I can't get it to update.
When the user logs in I set the session vars like
array('users'=>array('timezone'=>'America/los Angeles'));
I can then retrieve the data as follows: $_SESSION['users']['timezone']
and it works fine.
However in the user profile page the user can change their timezone and when I try to update the $_SESSION as follows it doesn't work:
$_SESSION['users']['timezone'] = 'America/Denver';
What am I doing wrong?
--- More code as requested -------
I found that the session variables were being set by a function inside of a class
Here's the function:
function session_var_register($object_name, $var_value)
{
$_SESSION[$object_name]=$var_value;
}
Here's how the function got called:
$gf->session_var_register("users", $user_array)
Users Array looks like array('users'=>array('timezone'=>'America/los Angeles'));
I don't understand why this doesn't work. I was able to get around the problem though by bypassing the function call and just creating the array like:
$_SESSION['users'] = $user_array;
But for knowledge reasons and if anyone else comes along this post, could anyone explain what the function was doing different? There were no errors thrown, just would not allow me to assign anything to the session variable once it was registered via the function...almost acted like it became read_only once instantiated.

Make sure you session_start() on every page that accesses the $_SESSION variable.

Sounds like the code that updates it may not be getting executed. You might try putting some kind of debugging statement before this assignment like an echo to verify that the action is being taken.

Following on from Scott's reply, double checking your session is started is a good "start".
There's a good tip here which you may find useful in debugging.

re-initialize your session id. That way you are sure it has a new spanking id to store your variables.

Are you doing a redirect soon after this code?
Do a session_write_close() before doing a redirect so that session vars are stored again before redirecting.

Related

PHP ignoring if statement, unsetting session vars

I have a PHP script that stores a url from which a form was submitted in a session variable and then compares it to the current page url. If it's not the same as the one stored in the session it gets unset, at least that's how it should work. The problem is that the if statement used for checking if the two urls match seeems to be ignored and the session vars get unset anyway.
$compare_url_old = array_shift(explode(',', $_SESSION['search_page']));
$compare_url_new = array_shift(explode(',', $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']));
if ($compare_url_new != $compare_url_old)
{
unset($_SESSION['search_page']);
unset($_SESSION['search_price_min']);
unset($_SESSION['search_price_max']);
unset($_SESSION['search_name']);
}
The strange part is that if I try to echo something within the if statement it works properly but for some reason the unset functions get called every time despite the result.
Problem solved, turns out it was something I overlooked above the code in question, the script works fine. Sorry for that.

Pass encrypted variable between browser windows in PHP

I'm desperately trying to pass a variable between browser windows. I have a php page (test.php) which opens another page (another.php) in new window. I also have some variable that needs to be encrypted/decrypted and passed WITH encryption password. I've created a session like this:
session_start();
$_SESSION['test'] = array(
'var1' => $encryption_password,
'var2' => $some_encrypted_stuff
);
But of course in new window 'test' session is NULL. I've tried different options, but all failed. I do can create a file and write data there, but this doesn't seem secure to me.
Can anybody give me a working example for this issue? Can't find anything by myself.
UPDATE
OK, my main task is to encrypt variable in one php file and decrypt in another. There's one condition tho: encryption password can NOT be read from initial storing place by 2nd php file - only by the the 1st one.
As far as I'm concerned, writing it to a file is probably NOT a good approach. You're trying to achieve a variable retrieval, and nothing more.
I'm not sure why your test variable is null. I just tried making this test myself and I could access everything just fine.
Your code that you provided SHOULD be writing the data to the session variable. First, be sure you're not killing the session somewhere later in that first script. Second, double and triple check your code to access the session variable. Without seeing your code it's hard to tell, but on the second page my only guess is that you're either misspelling the access to the variable, or you're forgetting to start the session again!
Here is the code for both of my files:
First page:
<?
session_start();
$_SESSION['test'] = array('var1' => "somevalue", 'var2' => "someothervalue");
?>
<a href='other.php'>Go</a>
Second page:
<?
session_start();
var_dump($_SESSION['test']);
?>
That works fine for me- I get the full session variable spat back out. Give it a shot and let us know if you're still having issues (with more of your code so we can better understand whats up). Good luck!

Naming a $_SESSION var from $_SERVER['REQUEST_URI'] keeps mysteriously naming the page "blank.gif"

Seems like such a simple problem but I'm out of options here...
So I want to set up a session variable that tells me the last page visited. I thought I could do this by declaring 2 session variables in a php include at the top of every page.
session_start();
if(!$_SESSION['this_url']){
// will only be declared once
$_SESSION['this_url'] = $_SERVER['REQUEST_URI'];
}
if($_SERVER['REQUEST_URI'] != $_SESSION['this_url']){ //dont update var on page refresh
$_SESSION['last_url'] = $_SESSION['this_url'];
$_SESSION['this_url'] = $_SERVER['REQUEST_URI'];
}
Simple enough right? But for an output it gives me this:
$_SESSION['this_url'] = /support/interactive.php (correct)
$_SESSION['last_url'] = /products/compatibility/blank.gif (right path, but blank.gif? wtf?)
it SHOULD be outputting "/products/compatibility/somepage.php" but it always replaces the page name with blank.gif.
I did a sitewide search on my site and nothing else is using my variable names. I even changed the var names and still same result. blank.gif is found in some jQuery scripts - so I suspect this may be where its coming from. But still... I'm declaring these things as the first piece of script on the page and outputting them immediately after declaring them. Is my Apache server messed up or what? this doesnt make sense.
Any ideas would be greatly appreciated, thanks!
Hmm, I remember trying to do something like this a while back, and I was having odd ghost problems much like you. What I ended up doing was using hidden inputs and assigning the variables to them.
I'm not saying use hidden form elements for production, I'm just making a suggestion in case the feature you are creating is a "need now" kind of feature.
I'm still looking as to why that may happen though, what version of Apache/PHP are you running?

Unassigning a variables value from $_GET

I use;
$referrer = $_GET['_url'];
If I echo $referrer; it will display correctly.
If I use $referrer within a $_POST, it is empty. I think due to $referrer being assigned to $_GET.
How can I extract the value of $referrer into another variable so it is no longer assigned to the $_GET?
I hope that makes sense..
$_POST will only contain data IF you send that from form.
So, your code is basically right. Because you use referrer from within your URL.
If you really want to have $referer from $_POST, you will have to code something like this:
<form method="post" action="somewhere.php">
<input type="hidden" name="_url" value="{place the referrer here}" />
</form>
Or, like #Michael Gillette answer, you can change that with $_REQUEST.
hope that makes sense..
sorry, but it doesn't :)
$referrer become distinct variable with no relation to $_GET['_url']. It already contains value extracted from $_GET
there are not a single reason for $_GET sourced variables to conflict with $_POST.
Your problem is somewhere else.
It seems you're just trying to access variable that doesn't exist. Because every variable dies along with whole PHP after it's execution.
PHP scripts execution is atomic. It's not like a desktop application constantly running in your browser, and not even a demon with persistent connection to your desktop application. It's more like a command line utility - doing it's job and exits. It runs discrete:
a browser makes a call
PHP wakes up, creates an HTML page, sends it to the browser and dies
Browser renders that HTML and shows it to the user.
User clicks a link
a browser makes a call
another PHP instance, knowing nothing of the previous call, wakes up and so on
So, if you set your $referrer in one instance and trying to access it in another, it will fail. You have to re-sent it's value with next call
Use the clone keyword, as seen in the examples in this article:
http://php.net/manual/en/language.references.php
could you post an example of what you might like to do?
$referrer = $_REQUEST['_url'];
will return true on both GET and POST requests

PHP - Pass POST variables with header()?

I'm trying to use the header() function to create a redirect. I would like to display an error message. Currently I'm sending the message as a parameter through the URL, however this makes it look quite ugly.
Is there a way to pass this value as a post variable instead?
Any advice appreciated.
Thanks.
Dan, You could start and store a session in PHP then save the message as a session variable. This saves you from having to transfer the message in an HTTP request.
Manipulating Sessions
//Start the session
session_start();
//Dump your POST variables
$_SESSION['POST'] = $_POST;
//Redirect the user to the next page
header("Location: bar.php");
Now, within bar.php you can access those POST variables by re-initiating the session.
//Start the session
session_start();
//Access your POST variables
$temp = $_SESSION['POST'];
//Unset the useless session variable
unset($_SESSION['POST']);
To read more about sessions, check out: http://php.net/manual/en/function.session-start.php
The header function is used to send HTTP response headers back to the user so actually you cannot use it to create request headers :(
One possibility is to use the CURL but I don't think it is worth of what you are doing.
Provided that you have local access to the page displaying the error, instead of redirecting you could include it in the page which caused the error and then programmatically display the error message.
if(something_went_wrong()) {
require_once('errors.php');
display_error('something really went wrong.');
}
The errors.php file would then contain a definition for display_error($message), which displays the formatted message.
When passing variables between modules I have found it easier to construct an array from the variables, convert the array to json and store it in a db table with two columns, a varchar key and a text data. The json would go in data and the key could be anything you want. Then in the target module you just read that back, convert the json back to an array and voila, you have your variables. No $_POST, no $_SESSION, no fuss, no muss, quick and easy. Of course that assumes you have access to a database, although you could use a file on the server. $_POST is useless since it needs a and $_SESSION can be cranky and can lead to unexpected results. Otherwise you'd almost have to use ajax.

Categories