在PHP(和安全性)中检索MySQL全文搜索的匹配上下文

cho*_*ata 6 mysql security search full-text-search

我在我的MySQL表"页面"上进行全文搜索.我正在显示与其"标题"(纯文本,VARCHAR,255)或"内容"(html,TEXT)中的关键字匹配的页面列表.当在"内容"字段中找到匹配项时,我想显示找到匹配项的代码段.我不知道该怎么做.

你能把我放在正确的方向吗?

$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>';       
}
Run Code Online (Sandbox Code Playgroud)

另外,我有一个关于安全性的问题.现在我正在检查$keyword三种方式:

  • 不是空白?
  • 超过2个字符?
  • 不危险?(见下文)

我使用正则表达式来匹配以下内容,以查看用户输入是否危险

<script|&lt;script|&gt;script|document.|alert|bcc:|cc:|x-mailer:|to:|recipient|truncate|drop table
Run Code Online (Sandbox Code Playgroud)

这可能有点荒谬且易于解决,但它至少是针对XSS漏洞利用的最小形式的保护.安全过滤用于搜索的关键字的推荐方法是什么?PHPIDS是否过度杀伤

glo*_*mad 7

这应该让你开始在"上下文"部分......

// return the part of the content where the keyword was matched
function get_surrounding_text($keyword, $content, $padding)
{
    $position = strpos($content, $keyword);
    // starting at (where keyword was found - padding), retrieve
    // (padding + keyword length + padding) characters from the content
    $snippet = substr($content, $position - $padding, (strlen($keyword) + $padding * 2));
    return '...' . $snippet . '...';
}

$content = 'this is a really long string of characters with a magic word buried somewhere in it';
$keyword = 'magic';
echo get_surrounding_text($keyword, $content, 15); // echoes '... string with a magic word in it...'
Run Code Online (Sandbox Code Playgroud)

此功能不考虑填充边界将超出内容字符串的情况,例如在内容的开头或结尾附近找到关键字的情况.它也没有考虑多个匹配等.但它应该至少指向你正确的方向.