猜数字游戏的问题

时间:2009-02-13 14:41:13

标签: php

嘿,我非常接近于猜测一个数字游戏,在PHP中非常简单,但出于某种原因,我被卡住了。我将变量存储为隐藏形式,但显然每次发送页面时都会重置数字,因此您永远无法获得正确的变量。

有什么想法吗?我的代码如下。

<?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">
<html xmlns="http://www.w3.org/1999/xhtml">
<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>

4 个答案:

答案 0 :(得分:3)

是不是因为这个错字?

$numbe  = $_POST['number'];
//numbe -> number

答案 1 :(得分:3)

变化:

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

要:

if(isset($_POST['number'])) {
   $number = $_POST['number'];
} else {
   $number = rand(1,100);
}

答案 2 :(得分:2)

我意识到你可能刚刚开始,但越早学习这些东西越好:

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

这让您对XSS攻击持开放态度 - 我可以$_POST['number']发送<script> doSomethingBad(); </script>

您应该将其转换为整数($number = (int)$_POST['number'])或转义输出(echo htmlspecialchars($_POST['number']);

当然$guess同样如此。

有趣的是,如果你正在使用mod_rewrite,$_SERVER['PHP_SELF']也可以被操作来做同样的事情。

答案 3 :(得分:1)

做类似的事情:

$number  = $_POST['number'];
if ($number == null) {
    $number = rand(1,100);
}