有什么想法吗?我的代码如下。
<?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>
答案 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);
}