PHP when are $_SESSION vars evaluated? - php

So my issue is that I'm setting a message in a session var to carry over in a page redirect.
And then setting the var to an empty string so it doesn't redisplay everytime.
Like so:
if ($successMsgs || !empty($_SESSION['msg_success'])) {
$success_block[] = '<ul id="success-block">';
foreach($successMsgs as $success) {
$success_block[] = '<li>'.$success.'</li>';
}
if (!empty($_SESSION['msg_success'])) {
$success_block[]='<li>'.$_SESSION['msg_success'].'</li>';
$_SESSION['msg_success']='';
}
$success_block[] = '</ul>';
$success_block = implode('',$success_block);
}
The problem is that the clearing of the session var seems to have a retro-active effect so the message never gets displayed. It only works if I take out the line that re-sets it to an empty string. I'm thinking there's something about when session vars are evaluated that I don't understand?

Except for the freedom to define functions and classes after invoking them, there is definitely nothing retro-active in PHP. Session variables will be available after the session_start() command. Unsetting a session variable inside the block won't have an effect in the code before it occurs.
Your problem must have to do with something else - maybe the page gets called twice, or a header redirect takes place?

It turned out that the code beneath the redirect was getting run, before actually redirecting. The solution was simply to add an exit to the redirect function.

well, the only possibility i can think of is that you are calling this piece of coding twice. and in the first call it doesn't get printed. maybe you are redirecting twice for some reason...

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.

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?

Redirecting Pages with PHP causing problems

I have a page which has a link to a php page which takes data from $_GET and updates a database. After that it returns the user to the homepage with:
header("Location: http://localhost/");
The thing is that this seems to "interrupt" the mysql part of the code. If I remove this redirect, everything in the database is updated, but when I put it back, nothing gets updated...
This is the database update code, I am using a class of mine as a mysql wrapper:
$conn->where('hash',$data1['hash']);
$conn->update(TABLE_ITEMS,$newData1);
$conn->where('hash',$data2['hash']);
$conn->update(TABLE_ITEMS,$newData2);
Notes:
-There is no text or echo()'s on the page and no space before the <?php tag
Order of Code:
Data received from $_SESSION and $_GET
Data processed and placed into arrays
Data placed into mysql database
header(); used to redirect page
Code
<?php
require_once('config.php');
import();
if ( isset ( $_GET['g'] ) && isset ( $_SESSION['itemA'] ) && isset ( $_SESSION['itemB'] ) ) {
$itemA = $_SESSION['gameA'];
$itemB = $_SESSION['gameB'];
$newData1 = processData($itemA);
$newData2 = processData($itemB);
$conn->update(TABLE_ITEMS,$newData1);
$conn->update(TABLE_ITEMS,$newData2);
header('Location: http://localhost/');
} else {
header('Location: http://localhost/');
}
If you send a header when previously content is outputted, you will get an error that may cause your script to stop execution. So if the header is above the update, the update may not be executed at all. It depends on your settings whether you see this error or not.
<?
echo 'yo';
header('Location: ....'); // <-- error
Update(); // Never gets executed
The output doesn't have to be an echo. It can even be a single space before the opening <?.
Without seeing much of the code, it's hard to be certain, but my guess would be that the PHP page is continuing to work exactly at it was before. What I would suggest might be happening is that the redirected page (ie your home page) is itself doing some database work which is overwriting the changes that had been done by the original page.
As I say, that's quite a wild guess in the absence of any more code (or even any detail about the data in question or what the site does), but I'd say it's worth investigating that possibility.
Try putting ob_start() at the top of the file. It sometimes helps. You can't output before calling header().
Show more code. It's to less of it to think what is wrong.
I have no idea why this worked, but it turned out that if I change this:
header("Location: http://localhost/");
to this:
header('Location: http://localhost/');
everything works. Weird!!

php session variable not updating a 2 dimensional array after initializing

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.

Strange problem with PHP and sessions

So the basis of this page is I set a session value when the page loads, and clear it on any other page they visit. Then the page can make an ajax call to download a file. If the session value matches the value I pass through the URL I allow them to download the file. If not I return a 404 error. I was having some weird issues, so I removed the 404 and set it to echo out the values instead to see what I was getting. Here is the top of the code on the page:
$code = $this->_request->getParam('code');
$confirm = $_SESSION['mp3_code'];
echo $code."-1-".$confirm;
if($code != $confirm)
echo $code."-2-".$confirm;//header("HTTP/1.1 404 Not Found");
else
{
Here is what displays on the page from the ajax call
12723430-1-12723430-2-
As you can see when it echos out the first time they exist, then somehow after I compare them and it fails you see that it echos out blank values like they suddenly ceased to exist. Any ideas?
It is imperative that you make sure to call session_start at the top of any script using sessions. I think this may be the case here.
In your code, it's echoing $code and $confirm. But $confirm is an empty string since you are not actually retrieving the session data (why has yet to be determined), the condition will most of the time evaluate to TRUE.

Categories