PHP $ _GET和$ _POST变量无法正常工作

时间:2016-07-22 20:48:43

标签: php post get

我的代码中有一个错误,可能看起来非常简单,但是我已经看了好几个小时,而且还没有能够确定问题。

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

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

根据您的代码,您将永远不会同时拥有$_GET案例和$_POST案例。单击链接(页面URL将包含$_GET查询字符串)后,您将点击?id=...案例,并在提交表单后点击$_POST案例(无查询字符串)。< / p>

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

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

相关问题