我在我的MySQL表「頁面」上進行全文搜索。我在其「標題」(純文本,VARCHAR,255)或「內容」(html,TEXT)中顯示與關鍵字匹配的頁面列表。當在「內容」字段中找到匹配項時,我想顯示找到匹配項的片段。我不知道如何去做這件事。在PHP(和安全)中檢索MySQL全文搜索的匹配上下文
你能幫我正確的方向嗎?
$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](http://php.net/manual/en/ref.pdo-mysql.php)。否則,你應該至少通過'mysql_real_escape_string()'運行'$ keyword'。 – glomad 2011-03-04 01:07:50
您的xss保護功能很弱。另外它可以安全地說'drop table'可以**永遠不會**攻擊這個代碼,因爲'mysql_query()'不允許查詢堆棧。 – rook 2011-03-04 03:23:53
@itchy謝謝,我將研究'PDO',但現在我只使用'mysql_real_escape_string()',謝謝。 @Rook,感謝您的見解,我意識到這一點,這就是爲什麼我要尋找替代品。 – maartenmachiels 2011-03-04 10:16:15