【问题标题】:PHP $_GET and $_POST variables are not working properlyPHP $_GET 和 $_POST 变量不能正常工作
【发布时间】:2016-11-26 20:43:09
【问题描述】:

我的代码中有一个错误,可能看起来非常简单,但我已经查看了几个小时,但仍无法确定问题所在。

要编辑数据库记录,我使用以下链接将记录 ID 传递到编辑页面:

<a href="edit_short.php?id=<?php echo $short->id; ?>">Edit</a>

...这里是edit_short.php 文件:

$title = "";
$short_text = "";
$id = 0;

if (isset($_GET['id'])) {
  $id=$_GET['id'];
  $short = (object)Short::find_by_id($id);

  $title = $short->title; // My problem is the scope of $title and $short_text
  $short_text = $short->short_text; // Is limited within this if statement
}
if (isset($_POST['edit_short_btn'])) {
  echo $title."<br/>";
  echo $short_text."<br/>";
}

这是提交的表单:

  <form method="POST" action="edit_short.php" id="post_form">
    <table>
      <tr>
        <td><input type="text" name="title" value="<?php echo $title; ?>" class="textField" placeholder="Title of short"></td>
      </tr>
      <tr>
        <td><textarea name="short_text" id="short_text" placeholder="Short text"><?php echo $short_text; ?></textarea></td>
      </tr>
      <tr>
        <td><input type="submit" name="edit_short_btn" value="Update short"></td>
      </tr>
    </table>
  </form>

我能够验证提交的 id 是使用 $_GET['id'] 设置的,并且我可以将其值传递给 edit_short.php 中的 $id,但是当我获取记录并设置 $title 和 $short_text 变量时,我是无法在if (isset($_POST['edit_short_btn'])) 语句中访问它们。

如何检查$_GET['id'] 和$_POST['edit_short_btn'] 是否已设置并且仍然能够显示$title 和$short_text?

【问题讨论】:

  • 对不起@chris85,id 是从表格中获得的,当我单击问题开头显示的链接时,显示的表格与此id 没有任何关系,所以我还没有明白将id 作为隐藏输入传递的意思
  • 表单在edit_short.php 文件中,应该包含要更新的记录的先前值。表单正在提交给edit_short.php,id 来自上一页(对不起,我没有包括在内)
  • 哦,现在我明白你的意思了。非常感谢,我不需要确认。它会工作
  • 如果答案解决了您的问题,请接受。

标签: php post get


【解决方案1】:

根据您的代码,您永远不会同时拥有$_GET 和$_POST 的情况。点击链接后您将点击$_GET 大小写(页面URL 将包含?id=... 查询字符串),提交表单后将点击$_POST 大小写(无查询字符串)。

【讨论】:

    【解决方案2】:

    GET 仅在点击链接时发送。您的表单正在发送POST,因此您想要的所有数据点都应该在表单中。您可以使用hidden 输入类型在表单中隐藏值。所以你应该可以使用:

    <form method="POST" action="edit_short.php" id="post_form">
        <input type="hidden" value="<?php echo intval($_GET['id']);?>" name="id" />
        <table>
          <tr>
            <td><input type="text" name="title" value="<?php echo $title; ?>" class="textField" placeholder="Title of short"></td>
          </tr>
          <tr>
            <td><textarea name="short_text" id="short_text" placeholder="Short text"><?php echo $short_text; ?></textarea></td>
          </tr>
          <tr>
            <td>
    </form>
    

    然后在您的处理脚本上使用$_POST['id'] 以获取id。 intval 是一种 XSS 预防方法,因为 id 将只是一个整数。有关防止 XSS 注入的其他方法,请参阅(这不会阻止 SQL 注入,仍应在处理脚本上使用参数化查询):

    How to prevent XSS with HTML/PHP?
    https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 2012-03-30
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多