我正在构建一个数字猜谜游戏,需要创建一个会话变量来保存随机目标数,直到用户提交正确的猜测。我还需要在用户提交正确答案后打印尝试次数。
我设置了会话变量并使用隐藏字段来保存计数器。当我提交猜测时,我不知道隐藏字段是否工作,我的代码打印出check()函数的第一个if语句.ALL THE TIME。
我认为它与会话变量(当然还有我的代码)有关,但我无法弄明白。我已经在这两天工作并且感到沮丧。任何帮助都会很棒。以下是我的完整代码:
<?php session_start() ?>
<!DOCTYPE HTML>
<html>
<head>
<title>Number Guessing Game</title>
</head>
<body>
<h1>Guess the number</h1>
<p>I'm thinking of a number between 1 and 5. Can you guess what it is?<br>
In less than 3 tries?</p>
<?php
extract($_REQUEST);
error_reporting(E_ALL & ~E_NOTICE);
// check to see if this is start of game
if (filter_has_var(INPUT_POST, "guess")) {
check();
} else {
setTarget();
} //end if
// set targetNum session variable
// increment counter by 1
function setTarget() {
$targetNum = rand(1, 5);
$_SESSION["targetNum"] = $targetNum;
$counter++;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
}
function check() {
global $counter;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess"
value= "$guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
if ($guess == $_SESSION['$targetNum']) {
print "<h3>Awesome. You guessed it in $counter attempt(s)</h3>";
unset($_SESSION["targetNum"]);
$count = 0;
print "<a href='numberGuessingGame.php'>TRY AGAIN</a>";
} else if ($guess > $_SESSION['$targetNum']) {
print "<h3>Too high. Guess again.</h3>";
} else if ($guess < $_SESSION['$targetNum']) {
print "<h3>Too low. Guess again.</h3>";
} else {
print "I don't know what that is...";
}
}
?>
</body>
</html>
答案 0 :(得分:0)
您的$guess
变量永远不会设置为POST值(更正:您正在使用提取,但我建议不要使用它)。您还在添加'$'时更改会话数组键的值:
$guess = $_POST['guess'];
if ($guess == $_SESSION['targetNum']) {
答案 1 :(得分:0)
你做了两个基本但严重的错误。
首先:开发时不要设置错误级别以排除通知!这样你就不会在变量或数组索引名称中发现拼写错误。移除error_reporting(E_ALL & ~E_NOTICE);
,或将其替换为error_reporting(E_ALL);
。
第二:您使用extract($_REQUEST);
- 使用该功能会遇到麻烦。由于“register_globals”功能,PHP具有很长的安全漏洞历史,它引入全局变量只是因为解析了请求数据中的某些key = value对。删除该功能花了数年时间。您正在使用该功能在没有任何安全预防措施的情况下重新实施它,并且没有任何实际好处。
删除extract($_REQUEST);
函数,并对来自远程浏览器的所有变量使用$_REQUEST['varname']
而不是$varname
。