在PHP中提交表单后,如何(安全地)保存搜索表单中的字段值?
这种方法安全吗?
<input type="checkbox" ... ="<?php if(isset($_POST['ThisRadioIsChecked'])) echo 'checked="checked"'; ?>" ... />
答案 0 :(得分:1)
如果你有类似的话:
<form action="this_page.php" method="post">
<input type="text" name="search" placeholder="Search..." value="">
<input type="submit" value="Go">
</form>
您可以使用$_POST
数组设置搜索输入值(如果使用GET方法,则设置为$_GET
。)
<?php
// if data 'search' posted in POST method, make it safe in HTML then store it in $search. If 'search' data was not posted, fill it with an empty string ('')
$search = (isset($_POST['search'])) ? htmlentities($_POST['search']) : '';
?>
<form action="this_page.php" method="post">
<input type="text" name="search" placeholder="Search..." value="<?= $search ?>">
<input type="submit" value="Go">
</form>
我必须向您解释,如果您的php.ini文件包含:short_open_tag = Off
然后您将不得不使用标准方法来执行此操作:<?php echo $search; ?>
而不是简短的方法:<?= $search ?>
顺便说一下,对于没有高级用户来说,这条线可能有点令人困惑:
$search = (isset($_POST['search'])) ? htmlentities($_POST['search']) : '';
您可以通过以下方式替换它:
if(isset($_POST['search']))
{
$search = htmlentities($_POST['search']);
}
else
{
$search = '';
}
甚至:
$search = '';
if(isset($_POST['search']))
{
$search = htmlentities($_POST['search']);
}
顺便说一句,如果你想不能保留价值:
<?php
// if data 'search' posted in POST method, make it safe in HTML then store it in $search. If 'search' data was not posted, fill it with an empty string ('')
$search = (isset($_POST['search'])) ? htmlentities($_POST['search']) : '';
// if reset asked, then empty $search
$search = (isset($_POST['reset'])) ? '' : $search;
?>
<form action="" method="post">
<input type="text" name="search" placeholder="Search..." value="<?= $search ?>">
<input type="submit" value="Go"><?php if($search != '') echo '<input type="submit" name="reset" value="Reset">'; ?>
</form>
您也可以使用复选框或其他内容...... :)