How to keep value in variable after refresh page in PHP? - php

I writing simple game. I randomizes two numbers and then user put your sum value number to input form whose I sent on the same site. Now if user guess sum numbers it he get 10 points, but if he will miss, lost one chance.
I have problem, because if i Refresh site i overiate he points and chance. Any solution?
$_SESSION['points'];
//$_SESSION['chance'];
$X = rand(1, 10);
$Y = rand(1, 10);
echo $X . " " . $Y;
?>
<form name="MyForm" action="" method="POST">
<input type="text" name="value">
<input type="hidden" value="<?= $X ?>" name="number">
<input type="hidden" value="<?= $Y ?>" name="number2">
<input type="submit" value="Generuj" name="Wynik?"/>
</form>
<?php
if (!empty($_POST) && isset($_POST)) {
$user = $_POST['value'];
if ($_POST['number'] * $_POST['number2'] == $user) {
echo ' ok !';
echo $_SESSION['points'] += 10;
} else {
echo 'error';
// echo 'You lost one chance' . $_SESSION['chance']--;
}
}

You can simply use a PHP session OR a PHP Cookie.
Using cookies (if information is not sensible)
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
?>
Then you can echo your cookie like this
<?php
echo $_COOKIE['TestCookie'];
?>
If you're using Sessions
<?php
session_start();
$_SESSION['myVar'] = $myValue;
?>
Then you can echo it that way
<?php
echo $_SESSION['myVar'];
?>
NOTE that with the session, you always have to start your session at the beginning of your PHP file.

Related

"How to have the user add two random integers on a single page using $_POST"

I am trying to create an adding game PHP and HTML, where the user guesses the sum of two random integers. However, when the user submits the answer, the integers randomize again, changing the sum and making the user's guess incorrect.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit']))
{
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I am expecting the output to be "nice, you got it right" when the $guess==$sum, but $sum changes when the form is submitted, making the 2 variables unequal.
Try to use session and store the two random number. PHP Session
just like this.
<?php
session_start();
if (isset($_POST['submit']))
{
$sum = $_SESSION['y'] + $_SESSION['x'];
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
$_SESSION['x']= (rand(1,10));
$_SESSION['y']= (rand(1,10));
echo "<br>What is " . $_SESSION['x'] . " + " . $_SESSION['y'] . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I hope I answer your problem. just read the PHP session it helps you a lot.
You can create a hidden input field to post the sum value. Then compare that value with the guessed value.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit'])) {
$guess = $_POST['guess'];
$value = $_POST['sum'];
if ($value == $guess) {
echo "nice, you got it right.";
} else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input type="hidden" name="sum" value="<?=$sum?>" />
<input name="submit" type="submit" />
</form>
You should store your $x and $y in a hidden input.
Calculate the sum by using the post value instead of generating new value.

Store post form values in hidden input array

I'm new to php and here's my code for a number guessing game. Since I don't know how to define a random number, I chose the number myself, 80. I'm trying to store all the guesses prior to the right one, and after the right guess, print them out on the screen. But I can't seem to be able to get it right since it only prints only the last guess before the right one.
Any help is appreciated!
<html>
<head>
</head>
<body>
<?php
$allguesses = array();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_POST["tmn"] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
array_push($allguesses,$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
foreach($allguesses as $x){
echo "<input type ='hidden' name = 'tmn[]' value=' ".$x . " '>";
}
?>
</form>
</body>
</html>
Sessions seem the best for where you are in your learning curve.
The session allows the normal stateless http protocol to remember things between each submission of a form or forms. So we will save each guess in an array of guesses in the SESSION, which in PHP is an array as well.
<?php
session_start(); // create a session, or reconnect to an existing one
if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["guess"]) ) {
$_SESSION['guesses'][] = $_POST["guess"]; // keep an array of guesses
// $t = $_POST["guess"]; no need for extra variables on the stack
$sayi = 80;
if($sayi > $_POST["guess"]){
echo 'Guess higher';
}elseif($sayi == $_POST["guess"]){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_SESSION['guesses'] as $guess){
echo $guess . ',';
}
$_SESSION['guesses'] = array(); // clear the old guesses out
}else{
echo 'Guess lower';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Removed uneeded codes.
Changed method of showing previous guesses with the below code.
echo implode( ", ", $_POST["tmn"] ); // cleaner
This block handles storing previous guesses into an array that is used for displaying previous guesses.
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
Fixed previous version of below block of code so that hidden <inputs> of previous guesses are outputted properly..
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
Updated Code:
<html>
<head>
</head>
<body>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
echo implode( ", ", $_POST["tmn"] );
}else{
echo 'Guess lower';
}
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
</form>
</body>
</html>
For random numbers you can use rand($min, $max). to store the guesses you can use the global variable $_SESSION.
<html>
<head>
</head>
<body>
<?php
//start session (needed to use the $_SESSION variable)
start_session();
if($_SERVER["REQUEST_METHOD"] == "POST"){
//if empty -> initalize array
if (empty ($_SESSION['allguesses']){
$_SESSION['allguesses'] = array ()
}
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
//echo all guesses from $_SESSION variable
foreach($_SESSION['allguesses'] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
//push in $_SESSION variable
array_push($_SESSION['allguesses'],$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

PHP Rand() resetting in maths game

I'm using PHP's Rand() function to generate two random numbers that I can compare against the user's, and echo out a success message if the user's answer equals (1st random number + 2nd random number.) However, I'm running into problems.
I suspected that the form was re-generating the numbers every time the form POSTED and the input was collected, so I tried using sessions instead to keep those numbers persistent. It's a mess to say the least.
I found this existing post: Problems with guess a number game , but the solution didn't remedy my problem.
<?php
if(empty($_POST))
{
$_SESSION['$number1'] = Rand(0, 100);
$_SESSION['$number2'] = Rand(0, 100);
}
if($_POST["submit"])
{
$input = $_POST['input'];
if($input == ($_SESSION['$number1'] + $_SESSION['$number2']))
{
echo "Correct! ";
}
else
{
echo "Incorrect! ";
}
}
echo "<hr><br> What is... <b>" . $_SESSION['$number1'] . " + " . $_SESSION['$number2'] . "</b>";
?>
<form action="" method="post">
<input type="text" name="input">
<input type="submit" name="submit">
</form>
<?php
echo "<b>DEBUG ANSWER: </b> " . ($_SESSION['$number1'] + $_SESSION['$number2']);
?>
Any help would be appreciated!
I changed a few things, personally, I wouldn't use the session, rather user hidden inputs. (if you're worried about security.. you shouldn't be.. numbers game, not banking site)
<?php
//Create a function to generate the random numbers (So we can re-use it)
function generateNumbers()
{
$one = Rand(0, 100);
$two = Rand(0, 100);
//Now return the random numbers
return array('number1' => $one, 'number2' => $two);
}
//Check if the submit button has been clicked
if($_POST["submit"])
{
$input = $_POST['input'];
if($input == $_POST['number1'] + $_POST['number2'])
{
echo "Correct! ";
}
else
{
echo "Incorrect! ";
}
}
//Now we create the numbers
$numbers = generateNumbers();
echo "<hr><br> What is... <b>" . $numbers['number1'] . " + " . $numbers['number2'] . "</b>";
?>
<form action="" method="post">
<input type="text" name="input">
<input type="submit" name="submit">
<!-- Personally I would rather use hidden inputs, than use the session -->
<input type="hidden" name="number1" value="<?php echo $numbers['number1'] ?>" />
<input type="hidden" name="number2" value="<?php echo $numbers['number2'] ?>" />
</form>
<?php
echo "<b>DEBUG ANSWER: </b> " . ($numbers['number1'] + $numbers['number2']);
?>

How to validate form input on the same page by using random numbers?

Would be awesome if you could help me out! I am trying to build a simple page to display random math questions. The answers should be typed in by the user and should be validated on the same page, giving him feedback on success and failure.
The problem is that by submitting the form input to the same page (I called it "form6.php") the page reloads and a new set of numbers is generated - that is why the "solution" variable is newly defined and cannot be used to test the accuracy of the user's answer.
This is the code I have so far (works fine for fixed numbers but fails with the random number generation):
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
$solution = $number1+$number2;
echo "$number1+$number2=?";
?>
<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>
<?php
if(isset($_POST['answer'])){
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
?>
Any help is highly appreciated! Since I am not a professional coder, the more specific you can get, the better!
A POSTed form will reload your PHP script, causing 2 new rand() numbers to be generated. You're going to want to pass the solution in the form.
Edit: I updated the answer to show a quick solution for using random operands for verification. This was simply done by switching through a random integer. Please note that when using - or / you may receive non-integer numbers (3 / 58 or 15 - 86), so you may want to add some custom logic to prevent this.
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
switch(rand(0,3)) {
case 0:
$solution = $number1 + $number2;
echo "$number1+$number2=?";
break;
case 1:
$solution = $number1 - $number2;
echo "$number1-$number2=?";
break;
case 2:
$solution = $number1 * $number2;
echo "$number1*$number2=?";
break;
case 3:
$solution = $number1 / $number2;
echo "$number1/$number2=?";
break;
}
?>
<form action="form6.php" method="post">
Your Answer:<br><input type="integer" name="answer">
<input type="hidden" name="solution" value="<?php echo $solution; ?>">
<input type="Submit" value="Submit!">
</form>
<?php
if(isset($_POST['answer']) && isset($_POST['solution'])) {
if ($_POST["answer"] == $_POST['solution']) {
// Valid
} else {
// Incorrect
}
}
?>
If you don't want to include the solution in your form (be it hidden), you have to store solutions in a separate text file in which you can, for instance, serialize your data.
Alternatively, you can use sessions or cookies.
But you have to store the solution somewhere.
Here is an attempt with sessions:
<?php
session_start();
$nb1 = rand(1,100);
$nb2 = rand(1,100);
$_SESSION['number1'] = $nb1;
$_SESSION['number2'] = $nb2;
$_SESSION['solution'] = $nb1 + $nb2;
// (...)
if(isset($_POST['answer']))
{
if ($_POST["answer"] == $_SESSION['solution'])
{echo "That's right";}
else
{echo "That's wrong!";};
unset($_SESSION['nb1']);
unset($_SESSION['nb2']);
unset($_SESSION['nbsolution']);
}
if(isset($_POST['answer'])===true){
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
If you are using isset($_POST['answer']) you must include === true at the end
Also make sure you use instead of integer.
#user3261573,
As pointed out by #Sam, you could pass the value in a hidden field, but, as #Jivan said, a better approach would be using a session to store the solution.
Here's the code:
Ps.: I simplified the code for a better understanding.
<?php
// Initiate session
session_start();
// If the FORM has been submited, verify answer
if( isset($_SESSION['solution']) === TRUE && $_SESSION['solution'] !== NULL && isset($_POST['answer']) === TRUE && isset($_POST['solution']) == TRUE ){
if( $_SESSION['solution'] == $_POST['answer'] ){
echo 'That\'s right';
}else{
echo 'That\'s wrong';
}
}
// If the FORM ain't submited yet, display the question
else{
// Random numbers
$number1 = rand(1,100);
$number2 = rand(1,100);
// Store solution in session for further comparison
$_SESSION['solution'] = $number1+$number2;
// Echo question
echo "$number1+$number2=?";
echo '<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>';
}
?>
If you like it, here's a few tutorials on using PHP SESSIONs:
http://www.w3schools.com/php/php_sessions.asp
http://www.php.net/manual/en/session.examples.basic.php
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
echo "$number1+$number2=?";
?>
<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
<input type="hidden" name="n1" value="$number1">
<input type="hidden" name="n2" value="$number2">
</form>
<?php
if(isset($_POST['answer'])){
$solution = $_POST['n1'] + $_POST['n2'];
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
?>

more than 1 form at one page

I've problem with multiple form at one page. At page index I include 4 forms
include('./poll_1a.php');
include('./poll_2a.php');
include('./poll_3a.php');
include('./poll_4a.php');
The form code at every poll page is the same. I include some unique markers ($poll_code) for every scripts but the effect is when I use one form - the sending variable are received in the others. But I would like to work each form individually.
The variable $poll_code is unique for every script -> 1 for poll_1, 2 for poll_2 etc.
The same situation is with $cookie_name
$cookie_name = "poll_cookie_".$poll_code;
than, as I see, cookies have different names.
$poll_code = "1"; // or 2, 3, 4
?>
<p>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" name="<?php echo $poll_code; ?>">
<input type="hidden" name="poll_cookie_<?php echo $poll_code; ?>" value="<?php echo $poll_code; ?>">
<table>
<?php
//print possible answers
for($i=0;$i<count($answers);$i++){
?><tr><td style="\text-allign: left;\"><input type="radio" name="vote_<?php echo $poll_code; ?>" value="<?php echo $i; ?>"> <?php echo $answers[$i]; ?></td></tr><?php
}
echo "</table>";
echo "<br>";
if ($_COOKIE["$cookie_name"] == $poll_code ) {
echo "<br> nie można głosować ponownie ...";
} else {
?>
<p><input type="submit" name="submit_<?php echo $poll_code; ?>" value="głosuj !" onClick="this.disabled = 'true';"></p>
<?php
}
?>
</form>
</p>
Q: how to make this forms to work individually at one page?
//------------------- EDIT
the receiving part of the script
$votes = file($file);
$total = 0;
$totale = 0;
$poll_cookie = 0;
if (isset($_POST["vote_$poll_code"]) && isset($_POST["poll_cookie_$poll_code"])) {
$vote = $_POST["vote_$poll_code"];
$poll_cookie = $_POST["poll_cookie_$poll_code"];
}
//submit vote
if(isset($vote)){
$votes[$vote] = $votes[$vote]+1;
}
//write votes
$handle = fopen($file,"w");
foreach($votes as $v){
$total += $v;
fputs($handle,chop($v)."\n");
}
fclose($handle);
Of course, the $file have the unique declaration too (at top of the script, under the $poll_code declaration).
$file = "poll_".$poll_code.".txt";
I think the issue might be that <?php echo $poll_code; ?> is outside the loop so maybe that it's always using the same value assigned to it, maybe put it inside the loop

Categories