【发布时间】:2026-01-27 18:50:01
【问题描述】:
我有一个搜索表单:
<form method="POST">
<input type="search" name="q">
<input type="submit" value="Search" name="search">
</form>
然后在 PHP 文件中:
if( isset($_POST['q']) ){
//Assigning the posted query to a variable.
$query = $_POST['q'];
//Get matches from the DB.
$stmt = $conn->prepare('SELECT * FROM posts WHERE title OR description LIKE :s');
$stmt->bindValue(':s', '%' . $query . '%', PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
//if there are matches.
if($count > 0){
//Get the matches.
$matches = $stmt->fetchAll();
foreach($posts as $post){
//Do Something.
}
}
}
现在我想一切都很好,为什么如果我执行以下操作:
<input type="search" value="<?php if(isset($_POST['q'])){echo $_POST['q'];} ?>" name="q">
或者:
<input type="search" value="<?php if(isset($query)){echo $query;} ?>" name="q">
这会导致攻击吗?
【问题讨论】:
-
不,这是完全可以接受的。您所做的就是回显访问者发布的值。换句话说:访问者取回发送的内容。它永远不会触及您的数据库(在您提供的最后两行代码中)。
-
奇怪的是没有其他人反应。好吧,让我这么说吧:我不喜欢 PHP 在属性值字符串中。基本上,您在输入标记内有一个 PHP 标记。这看起来很奇怪。你也没有逃避你插入的东西。所以你最终可能会得到损坏的 HTML。
-
如果用户把它放在你最后给定代码的输入中怎么办? :
"><script>alert('XSS');</script>当然是脆弱的 -
@MobinF.R.G,这和我的意思完全一样,有人用同样的东西回答了我之前的问题
-
@MobinF.R.G,在这种情况下,该警报不会仅针对该用户显示吗?
标签: php html mysql security pdo