Zahir Zahir - 1 month ago 7
PHP Question

How to keep the random value remain same in a session variable in php

I am new in php and trying to solve a simple problem like create a random number and store it in session variable so that
the value remain same for the entire session. I need to compare that value with user input from the same php page as below.

<?php

session_start();
//get a random number and store it in session variable
$_SESSION["random"] = rand(1,10);
$randomNumber = $_SESSION["random"];

if (isset($_POST['submit'])) {

$input = $_POST['input'];

if( $input > $randomNumber )
{
//code
}
else if($input < $randomNumber)
{
//code
}

}
?>


<html>
<body>
<form action="" method="post">
<label > Enter input to match:</label><br />
<input type="text" name="input" id="input" /><br /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Answer

You need to check if the random number variable is set, and if not generate it, if so then don't:

if(!isset($_SESSION["random"])) {
    $_SESSION["random"] = rand(1,10); 
}
$randomNumber = $_SESSION["random"];
Comments