挣扎着隐藏的表单领域基础知识(PHP)

0 php forms

我在使用PHP数据隐藏表单时遇到了困难.我不能为我的生活弄清楚我做错了什么.

我的代码应该

  1. 检查攻击是否成功;
  2. 如果成功,减去健康造成的伤害;
  3. 重写$ health变量.
  4. 使用新的$ health值进行下一轮.

问题是,它不断重置健康价值.

这是我的代码(它的设置使得攻击总是成功):

<?php
$health = $_REQUEST["health"];
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);
$health =50;

if ($attack>$defend){
    print "<p>Jim hit the robot for $damage.</p>";
    $health = $health - $damage;
    print "<p>The robot has $health health remaining.</p>";
} else {
    print "<p>Jim missed.</p>";
    print "<p>The robot has $health health remaining.</p>";
} // end if statement

print <<<HERE

<input type="text"
   name="openMonsterHealth"
   value="$health">
<input type="hidden"
   name="hdnMonsterHealth"
   value="$health">
<input type="submit"
   value="click to continue">

HERE;
?>
Run Code Online (Sandbox Code Playgroud)

Fra*_*ook 10

如果您希望$ health跟随您进入下一页,请使用会话.

PHP会议手册

基本上,你会用你的页面开始

session_start();
if(isset($_SESSION['health'])) {
    $health = $_SESSION['health'];
}
else {
    //However you normally set health when the user is just starting
}
Run Code Online (Sandbox Code Playgroud)

这将加载上一页的健康值,如果你这样设置:

$_SESSION['health'] = $health;
Run Code Online (Sandbox Code Playgroud)

PHP脚本自动编写和关闭会话,因此除了在会话全局数组中创建变量之外,您不必担心任何其他事情.当您想从上一页检索会话数组中的数据时,不要忘记启动会话.但是,您的用户必须能够接受cookie.

如果你继续使用隐藏字段,玩家可以在将信息发回给你之前更改该信息(此外,他们更难以跟踪).

编辑:


但是,您的错误是您在代码的第5行将健康状况重置为50,您没有使用正确的变量名称来处理请求中的健康状况,并且您没有任何表单标记.


<?php
if(isset($_REQUEST['hdnMonsterHealth']))
    $health = $_REQUEST['hdnMonsterHealth'];
else 
    $health = 50;
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);

if ($attack > $defend) {
print "<p>Jim hit the robot for $damage.</p>";
$health = $health - $damage;
print "<p>The robot has $health health remaining.</p>";
} else {
    print "<p>Jim missed.</p>";
    print "<p>The robot has $health health remaining.</p>";
} // end if statement

print <<<HERE

<form method="post">
<input type="text"
   name="openMonsterHealth"
   value="$health">
<input type="hidden"
   name="hdnMonsterHealth"
   value="$health">
<input type="submit"
   value="click to continue">
</form>

HERE;
?>
Run Code Online (Sandbox Code Playgroud)

编辑:抱歉所有的奇怪,格式被这段代码打破,所以我不得不手动插入<代码中的每一个&lt;.但是,此代码现在可以使用.

你还有一个负面健康的错误.不过,我不会为你写游戏.