-2

I am here storing the randomly generated value from rand() into $_SESSION['previous_rand']

. I am also echo both the current generated rand() and previously stored in $_SESSION['previous_rand']

but it showing the current generated rand() into the previously generated rand() field.

How can i make it show the previously generated rand() correctly?

<?php

session_start();

$rand = rand(1000,9999);
$_SESSION['previous_rand'] = $rand;


echo "Current generated RAND: " . $rand;
echo "<br>";
echo "Previously generated RAND: " . $_SESSION['previous_rand'];
  
?>
Emma Marshall
  • 354
  • 1
  • 12
  • 2
    You are setting session previous_rand before you echo "Previously generated RAND" so this code always returns newly generated $rand. – gguney Feb 19 '22 at 06:04
  • 2
    You're always generating a new value, and always saving that *SAME* value in both $rand and $_SESSION['previous_rand']. PHP is just doing what you're telling it to. – paulsm4 Feb 19 '22 at 06:04

1 Answers1

1
<?php

session_start();

$rand = rand(1000,9999);
//Here you were setting new $rand to previous_rand that's why.

echo "Current generated RAND: " . $rand;
echo "<br>";
echo "Previously generated RAND: " . $_SESSION['previous_rand'];
$_SESSION['previous_rand'] = $rand;
?>
gguney
  • 2,512
  • 1
  • 12
  • 26
  • The previously generated is blank? – Emma Marshall Feb 19 '22 at 06:08
  • Then you are not setting previous rand. Can you refresh the page and check it again? You may need to read how session works and how variable setting works and the order of code execution. Here is a link for that: https://stackoverflow.com/questions/1535697/how-do-php-sessions-work-not-how-are-they-used – gguney Feb 19 '22 at 06:12
  • 1
    That's actually works i uploaded it on actual web hosting site and i found out w3school is not a great place to test PHP since it automatically using `session_regenerate_id(true);` invalidating all `$_SESSION` – Emma Marshall Feb 19 '22 at 06:21
  • I did not know you are trying on w3school. Glad it solved. Have a nice day. – gguney Feb 19 '22 at 06:24