Google Chrome: PHP code would be executed twice when session was started - php

I need to set a dynamic id for every document load. This ID should be set in PHP. Now, when i set a session_start(), the php code would be executed twice because the ID-code in generated document source differs from the same code in the alerted script variable. There are no runtime errors.
What's wrong with this code and how can i prevent the session to re-execute my code after session_start() ?
And when the code would be executed twice (var idvar contains a different value) why the heck is alert executed only once?
I simplified the script so you can try for your self:
<?php
// Session start generates two different ID's
session_start();
// Create ID
$time = microtime(1);
$parts = explode('.', (string)$time);
$idvar = strtoupper(strrev(dechex($parts[0]) . dechex($parts[1]))) . dechex(rand());
?>
<script>
// Contains a new generated ID after session_start()
var IDvr = '<?php print $idvr; ?>';
alert(IDvr);
</script>
Screenshots:

Try move the id initialization just before session_start() i suspect it related on how things executed in php after session_start().
Edit
still unable to reproduce it

I found this:
PHP Session storing behavior into variables?
But even when i add a favicon to the page it don't works. Also the page is standalone and not included as require in another page.
Even this is not working!
// Session start generates two different ID's
if(!isset($_SESSION) && !isset($idvr)) {
session_start();
// Create ID
$time = microtime(1);
$parts = explode('.', (string)$time);
$idvr = strtoupper(strrev(dechex($parts[0]) . dechex($parts[1]))) . dechex(rand());
}
Update:
Now corrected:
With view-source:pgname and session initialized the code would be executed again in source view!

Related

PHP SESSIONS are empty after reload page

I have code
<?php
require_once("lib/functions.php");
$page = new page;
if(isset($_POST['jmeno'])){
$page->mailit($_POST, $_SESSION['result']);
}
$_SESSION['f'] = rand(1,9);
$_SESSION['s'] = rand(1,9);
$_SESSION['result'] = $_SESSION['f'] + $_SESSION['s'];
?>
Before POST form it prints the right values, but after POST form the sessions are empty. I don't know why, looks like something is bad configured. So it's always show Bad counted result
Here is session configuration....
make sure that this line of code:
session_start();
Is at the beggining of your php file, right after the opening php tag <?php
This line of code is used to start new or resume existing session, please see php manual here
Make sure that your file had UTF-8 encoding. (not UTF-8-BOM)

Inconsistent passage of session variable between pages

I'm having a problem passing a session variable from one page to another- in only ONE situation.
The problem is that sometimes the variable passes, sometimes, not.
About 50% of the time I need to refresh the second page (multiple times) to read the variable correctly.
When it doesn't read the "new" variable, the "old" session variable is used and brings up a different person.
I'm not "losing" the variable, it's just that the "new" variable isn't being read by the page.
Here's the layout:
.............................Page A
...............................|
...............................|
.............................Page B
...............................|
.............__________________|___________________
.............|.................|..................|
___________Page C...........Page D..............Page E
Page A is a list of people in rows taken from a db.
When you click on a row it "selects" the person with this code:
$("#patienttable tr").click(function() {
var passthis = $(this).find("#localid").html();
$.post("php/setsessionvariable.php",
{sessionval: passthis} );
window.location.href = 'http://www.xxxxxxxx.xxx/xxxxxx/xx/xxxx.php';
});
"patienttable" is the list of people.
"passthis" is the person identifier (from "localid").
"setsessionvariable.php" is the server side php file that sets the variable.
Here is the php file that sets the session variable (pretty boring, huh?)
<?php
session_start();
$_SESSION['patientidentifier'] = $_POST['sessionval'];
?>
In pages B, C, D, and E, the session variable is read by php code on the same page as the HTML, like this;
These are the first lines at the top of the file.
<?php
session_start();
$ptidentifier = $_SESSION['patientidentifier'];
...rest of php code to pull data from the db and post it on the page...
...html code...
...javascript code...
...end of page...
I have NEVER had a problem with moving from Page B to C, Page B to D, Page B to E, and back and forth...NEVER.
The problem is always from Page A to B.
Questions:
Can someone point me in the right direction to fix this?
Would you set a session variable like this? or a better way?
I thank you in advance.
your not finishing the post before redirecting to the next page. change your code as follows. it will then allow your post to finish before redirecting to the next page.
$("#patienttable tr").click(function() {
var passthis = $(this).find("#localid").html();
$.post("php/setsessionvariable.php",
{sessionval: passthis} , function (e) {
window.location.href = 'http://www.thedentons.us/easyehr/v2/root.php'
} );
;
});

Sessions not working properly

I wrote code for a web page that uses sessions. I'm using Mac and it is working fine. I tried my page on a Windows, and the sessions don't seem to work. It turns out the session variables I declare do not exist in the other pages. I used session_start() at the beginning of every page I have. One of the solutions I read about this problem was to use session_write_close() but it did not work. When I use var_dump() on $_SESSION I only see the ones declared in the same page (This is the case in both Mac and Windows). On windows and on Mac I used Chrome. And one of the reason I though it worked on Mac was because I didn't get an error, it just worked, however, on Windows, I get the line of error and it said the index of session I'm using is undefined.
What is the problem in my case? And how can I solve it?
EDIT:
Here is the code for setting the variables in session, this is the very first block of the page
<?php
session_start();
session_destroy();
$_SESSION["contestant_name"]["topics_done"] = array( FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE ); // topics done
$_SESSION["contestant_name"]["topics_score_correct"] = array();
$_SESSION["contestant_name"]["topics_score_wrong"] = array();
$_SESSION["contestant_name"]["correct"] = 0;
$_SESSION["contestant_name"]["wrong"] = 0;
?>
And here is code for reading variables
<?php
session_start();
if (isset($_POST["submit"]))
$name = $_POST["name"];
if(!isset($_SESSION["contestant_name"]["name"]))
$_SESSION["contestant_name"]["name"] = $name;
// if ($_SESSION["contestant_name"]["name"] == "")
// $_SESSION["contestant_name"]["name"] = $name;
print $_SESSION["contestant_name"]["name"];
$arr = $_SESSION["contestant_name"]["topics_done"]; // getting it as null or empty
var_dump($_SESSION);
print count($arr);
print_r($arr);
?>
Here is where I am trying to use the session variables after storing them in a previous page.
The code at the top of every page BEFORE anything else should be (make sure it's on the top line as I've put it)
<?php session_start();
ob_start();?>
And at the bottom of every page put:
<?php ob_end_flush();?>
Don't put anything before the first code or after the 2nd code.

Setting a cookie before page is refreshed/closed

I'm once again asking for the SO community for a little help.
I'm modifying a Joomla "quiz" component to make it behave the way I need it to.
What I'm trying to do now is to change the "refresh" behavior of the component. Basically, every quiz has a timeout, i.e., a time when the quiz is no longer accessible to the user so when the timer gets to 0, the quiz is submitted and so on, but the default behavior of this component makes it that whenever the page is refreshed the timer will reset to the initial set time (let's say, 10 minutes)
The thing is I want to be able to have the timer continue from where it left of in case of a refresh.
I haven't used PHP since 3 or 4 years ago so I'm kinda lost.
To be able to achieve the desired behavior I'm setting up a cookie that will store (via implode) the initial time (when the quiz was opened) and the "now" time (on load it's set to 0 but upon refresh I want to "update" the cookie to store the reload time).
With the initial time and the now time, I'll be able to calculate how much time has passed and place the timer from where it left off.
The thing is, I'm trying to "update" the cookie with a javascript 'onbeforeunload' so that I can manage to get the refresh time into the cookie. But for some reason, it's not doing anything at all. When I go to see the cookie contents everything is still the same from when the cookie was set.
I know that in order to update the cookie I'll have to delete it and then set it again, but I'm being unsuccessful.
Heres the sample code:
//This is responsible for setting the cookie (via PHP):
<?php
$name = "progress";
$now = 0;
$time_diff = 0;
$expire = time() + 3600;
$data = array(time(), $now, $time_diff, $this->quiz->time_limit);
//$var = implode(',', $data);
if(isset($_COOKIE[$name])) {
/* If defined, update the timer */
} else {
setcookie($name, implode(',',$data), $expire);
}
echo $_COOKIE[$name];
echo "<br />";
echo $this->quiz->time_limit;
?>
And this is to detect the "refresh" event (with Javascript that will run PHP):
window.onbeforeunload = function() {
<?php
$name = "progress";
$list = explode($_COOKIE[$name]);
//delete cookie
setcookie($name, "", time() - 3600);
//Update the fields
$list['1'] = time(); //now - refresh time
$list['2'] = $list['1'] - $list['0']; //time_diff
//Set the cookie again
setcookie($name, implode(',', $list), time() + 3600);
?>
}
Can anyone point out what is wrong with this code?
As has been said in the comments, JavaScript cannot run PHP code like that... but if you use AJAX then you can. Now with the code you posted for us to see, if you load up your page in the browser and view the code your function will look like this:
window.onbeforeunload(){
}
So it's no surprise that nothing is happening with your cookies when you are closing your browser. Now, without seeing your other functions it's hard to tell exactly what is happening but you can use PHP and JavaScript intertwined but in a different fashion. Let me explain this with an example.
window.onbeforeunload(){
var name = <?php $name='Steve'; echo($name); ?>;
console.log(name);
}
If you had this code and loaded the page in the browser you would no longer see the PHP code, but instead would see this:
window.onbeforeunload(){
var name = 'Steve';
console.log(name);
}
With that being said, here are a few links you might find helpful.
JavaScript Cookies
Set/Get Cookie using PHP and JavaScript
Simple AJAX - PHP and JavaScript

PHP $_SESSION variables not storing values

I'm trying to use PHP session variables to carry data over multiple pages. I am using session variables on many parts of my site, but this is the first place where they don't work.
I'm setting it like this:
$_SESSION["savedRetailerName"] = $foo;
And calling it like this:
echo $_SESSION["savedRetailerName"];
The session id remains the same between these two pages, and I'm sure that I'm setting the variables right and that they are being called right. I start the session correctly, and even on that particular page, other session variables are being shown properly.
How can I begin to debug this odd behavior?
Edit:
There are two different pages I'm currently dealing with. Page 2 sets the session variables, and there is a button that will return the user to Page 1. The idea is to still have the fields in Page 1 filled in if the user wishes to return to Page 1.
It is not a cache problem, and I can return other session variables in the exact same spot in my code as where I am failing to return these variables.
The only other code that may be pertinent is the back button handler (jQuery):
$('#backButton').live('click',function() {
window.location.replace("page 1");
});
Edit 2:
I believe this isn't working because of something with variables here:
<?php
$retailerName = $_REQUEST["retailerName"];
$description = $_REQUEST["description"];
$savingsDetails = $_REQUEST["savingsDetails"];
$terms = $_REQUEST["terms"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$zone = $_REQUEST["zone"];
$dateExp = $_REQUEST["dateExp"];
$tag = $_REQUEST["tag"];
$_SESSION["rn"] = $retailerName;
$_SESSION["de"] = $description;
$_SESSION["sd"] = $savingsDetails;
$_SESSION["tm"] = $terms;
$_SESSION["ph"] = $phone;
$_SESSION["ad"] = $address;
$_SESSION["zo"] = $zone;
$_SESSION["ex"] = $dateExp;
$_SESSION["tg"] = $tag;
?>
I am able to set any session variable to a string, but it won't set to a variable.
You want to use session_start before you set or use any session variables. You only need to call it once.
If it's working in other places, odds are that this particular block of code is being executed before session_start is called.
remove all non printable characters before <?php
you may not see them..
You have spaces before your <php tag
You don't have session_start() anywhere
You are using the $_REQUEST variable which is sketchy (use $_GET or $_POST instead)
You would also need to register the session using
session_register # php.net

Categories