【发布时间】:2011-07-08 11:44:12
【问题描述】:
我正在对我的 MySQL 表“页面”进行全文搜索。我正在显示与“标题”(纯文本,VARCHAR,255)或“内容”(html,TEXT)中的关键字匹配的页面列表。在“内容”字段中找到匹配项时,我想显示找到匹配项的 sn-p。我不知道该怎么做。
你能告诉我正确的方向吗?
$query = ' SELECT
*,
MATCH(title, content) AGAINST("'.$keyword.'") AS score
FROM
page
WHERE
MATCH(title, content) AGAINST("'.$keyword.'")
ORDER BY
score
DESC ';
$result = mysql_query($query) or die (mysql_error());
if(mysql_num_rows($result) > 0) {
$output .= '<p>Your keyword matches the following pages:</p>';
while($row = mysql_fetch_assoc($result)){
$title = htmlentities($row['title']);
$content = htmlentities(strip_tags($row['content']));
$content = limit_text($content, 250); // Cuts it down to 250 characters plus ...
$output .= '<h2>'.$title.'</h2>';
if(trim($content) != '') {
$output .= '<p>'.$content.'</p>'; // I'd like to place a snippet here with the matched context
}
}
} else {
$output .= '<p>Keyword not found...</p>';
}
另外,我有一个关于安全的问题。现在我正在通过三种方式检查$keyword:
- 不是空白?
- 超过 2 个字符?
- 不危险? (见下文)
我用正则表达式匹配下面的,看看用户输入是否危险
<script|<script|>script|document.|alert|bcc:|cc:|x-mailer:|to:|recipient|truncate|drop table
这可能有点荒谬且易于解决,但它至少是针对 XSS 攻击的最低限度的保护形式。安全过滤用于搜索的关键字的推荐方法是什么? PHPIDS 是不是矫枉过正?
【问题讨论】:
-
在回答您问题的安全部分时,请尽可能使用PDO。否则,您至少应该运行
$keyword到mysql_real_escape_string()。 -
您的 xss 保护很弱。也可以肯定地说
drop table不能永远攻击此代码,因为mysql_query()不允许查询堆叠。 -
@itchy 谢谢,我会调查
PDO,但现在我只使用mysql_real_escape_string(),谢谢。 @Rook,感谢您的见解,我意识到这一点,这就是我正在寻找替代方案的原因。
标签: mysql security search full-text-search