PHP$_GET和$_POST变量工作不正常


PHP $_GET and $_POST variables are not working properly

我的代码中有一个错误,这个错误可能看起来简单得离谱,但我已经看了好几个小时了,还没能确定问题所在。

要编辑数据库记录,我使用以下链接将记录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

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

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']来获得idintval是一种XSS预防方法,因为id将仅是一个整数。有关防止XSS注入的其他方法,请参阅(这不会停止SQL注入,参数化查询仍应用于处理脚本):

如何用HTML/PHP防止XSS
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_事件_备忘单