I’m being puzzled by the strange behavior of some session variables. The “token” variable in particular.
This is how I create it in index.php:
<?php
session_start();
$_SESSION['token'] = sha1(rand(7451, 98632)); // Lets name it "something"
?>
Then I do a POST with AJAX and pass that variable to another script, the ajax_io.php:
Inside the ajax_io.php:
<?php
session_start();
if($_POST['token'] != $_SESSION['token']) die('Horribly');
?>
My check always “dies”, while the token is passed correctly by the javascript AJAX post in index.php, the $_SESSION[‘token’] in the ajax_io.php is different than the one created in the index.php.
e.g. in ajax_io.php:
The $_POST['token'] appears as "something"
but,
$_SESSION['token'] appears as "something else"
It’s like if the AJAX post is requesting the index.php (somehow) that creates another token and then requests the ajax_io.php to do the functionality requested.
Here is the Javascript AJAX request:
var token = '<?php echo $the_token; ?>';
$.post("ajax_io.php", {
token: token
}, function(data) {
// Do something with data
});
UPDATE:
I haven’t mentioned that on the real script, there is a foreach loop, and that loop is the cause of the trouble. It somehow rewrites the php token variable with a newly generated one on each loop but the script keeps the original value for setting the javascript variable.
$the_token = sha1(mt_rand(10, 100));
$_SESSION['tokens'][] = $the_token; // Notice the multidimensional array here
foreach(somethin) :
// do something other than setting any session variable
endforeach;
print_r( $_SESSION );
Output:
Array (
[tokens] => array (
[0] => b19477cb038d6e0f588b6631c1686c8e246b82d5 // The real one created at the beginning of the script
[1] => 51e57c94bfd5c81b11e8c48dc8002b1162f4cd84
[2] => 084c881c074678218a4394524f60d3867da84cb3
)
)
On this script if I echo out the $_SESSION I get an N amount of tokens, for example 3. But only the first one is the one created physically by my script, the other 2 where created by the loop. I’ve gone through the entire loop script but haven’t found anything setting any sort of variables to the SESSSION.
Found out that the cause of the double request was an IMG tag on the rendered text inside the foreach loop. The tag had an empty src parameter, that was triggering a request in the background. That request was refreshing the generated key, but since it was in the background, the front-end part wasn’t getting the new key. Stupid problem.
This question in now solved. (I hope)