tags:

views:

511

answers:

4

Hey, I am so close to fininshing my guess a number game, very simple in PHP, but for some reason I am stuck. I am storing the variable in a hidden form, but obviously each time the page is sent it resets the number so you can never get the right one.

Any ideas? My code is below.

<?php
// generate a random number for user to guess
$number = rand(1,100);

if($_POST["guess"]){

    // grab the user input guess
    $guess  = $_POST['guess'];
    $numbe  = $_POST['number'];
    if ($guess < $number){ 
     echo "Guess Higher";
    }elseif($guess > $number){       
     echo "Guess Lower";
    }elseif($guess == $number){      
     echo "You got it!";
    }
    echo "<br />Random Number:".$number."<br />";
    echo $guess;
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Guess A Number</title>
</head>

<body>
<form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number">
    <label for="guess">Guess A Number:</label><br/ >
    <input type="text" name="guess" />
    <input name="number" type="hidden" value="<?= $number ?>" />
    <input name="submit" type="submit" />
</form>
</body>
</html>
+3  A: 

Is it because of this typo?

$numbe  = $_POST['number'];
//numbe -> number
Ates Goral
+3  A: 

Change:

// generate a random number for user to guess
$number = rand(1,100);

To:

if(isset($_POST['number'])) {
   $number = $_POST['number'];
} else {
   $number = rand(1,100);
}
Cory Dee
Thank you that got it to work, and it is not refreshing each time thanks to the conditional.Ryan
Coughlin
Also, the typo pointed out by Ates should be removed altogether with this solution (no need to reasign number, we already have it set).
Cory Dee
Appreciate it!Ryan
Coughlin
+1  A: 

Do something like:

$number  = $_POST['number'];
if ($number == null) {
    $number = rand(1,100);
}
ck
+2  A: 

I realise you're probably just starting out but the earlier you learn this stuff, the better:

echo "<br />Random Number:".$number."<br />";

This is leaving you open to an XSS attack - I could send $_POST['number'] as <script> doSomethingBad(); </script>

You should either cast it to an integer ($number = (int)$_POST['number']) or escape your output (echo htmlspecialchars($_POST['number']);)

The same goes for $guess of course.

Interestingly, if you're using mod_rewrite, $_SERVER['PHP_SELF'] could also be manipulated to do the same thing.

Greg