PHP Foreach Loop and Sessions - Strange Behavior
Posted: Sun Aug 14, 2011 6:14 am
Hello fellow PHP developers, this is my first post here. I'm trying to find a solution to a really weird problem I'm having with my script.
I'm trying to pass a token to the SESSION like this, in the index.php file:
This variable will get assigned to a Javascript variable as well, on the same index.php script. That variable gets sent by an AJAX request:
Then I have another script named, ajax_io.php, that is verifying that token after being send by an AJAX request:
The logic works, but for some odd reason the $_SESSION['token'] will get reset by another random SHA1 string and the test fails on the ajax_io.php script.
I should also mention at this point that the index.php has a Foreach loop that loops 3 times to display the tabbed interface.
The problem occurs at this point in the loop. As you can see I don't assign a newly random token to the session but for some odd reason it does it by itself. If I comment out the echo $data['html_string'];, the session token variable remains unaffected and the script logic functions as expected.
Any idea why would an echo statement, withing a foreach loop, trigger the 2nd line of script ($_SESSION['token'] = sha1(mt_rand(100, 10000));) again?
UPDATE:
Fixed a typo, was multitasking at the time and mixed up the loop types. It was a foreach loop and not a while loop!
I'm trying to pass a token to the SESSION like this, in the index.php file:
Code: Select all
session_start();
$_SESSION['token'] = sha1(mt_rand(100, 10000));Code: Select all
var the_token = '<?php echo $_SESSION['token']; ?>';
// jQuery Post
$("element").click(function() {
$.post('ajax_io.php', {
token: the_token
}, function(response) {
// Do something with response
});
Code: Select all
session_start();
if($_REQUEST['token'] != $_SESSION['token']) die("Horribly!");I should also mention at this point that the index.php has a Foreach loop that loops 3 times to display the tabbed interface.
Code: Select all
<?php
// pseudo-code
foreach(expression) : ?>
<div class="tab"><?php echo $data['html_string']; ?></div>
<?php endforeach; ?>Any idea why would an echo statement, withing a foreach loop, trigger the 2nd line of script ($_SESSION['token'] = sha1(mt_rand(100, 10000));) again?
UPDATE:
Fixed a typo, was multitasking at the time and mixed up the loop types. It was a foreach loop and not a while loop!