0

我有一个网站,用户可以通过输入关键字来搜索帖子,我正在使用 Sphinx 搜索进行全文搜索,everyhting 都按预期工作。

但是当我在搜索查询中输入/输入一些特殊字符时,搜索 dosnt 完成并引发错误。

例如我搜索的关键字:

hello)

我对 sphinxql 的查询:

SELECT id FROM index1 WHERE MATCH('hello)') 

我得到的错误:

index index1: syntax error, unexpected ')' near ')'

我的 php 代码看起来像这样

<?php
$sphinxql = mysqli_connect($sphinxql_host.':'.$sphinxql_port,'','') or die('ERROR'); 
$q = urldecode($_GET['q']);
$sphinxql_query = "SELECT id FROM $sphinx_index WHERE MATCH('".$q."') ";
?>

如何逃避用户输入并确保查询不会停止并返回结果集?

4

2 回答 2

5

应该使用 SQL 转义,以避免 SQL 注入。

http://php.net/manual/en/mysqli.real-escape-string.php

$sphinxql_query = ".... MATCH('".mysqli_real_escape_string($sphinxql,$q)."') ";

...但是您可能还想转义扩展语法。

在 sphinx 论坛 http://sphinxsearch.com/forum/view.html?id=13619

对于一个简单的解决方案。

该线程中的函数可用于使您的查询工作。它将转义 ) 并停止将其视为运算符。


但是,这也意味着您将无法使用任何搜索运算符 - 因为它会盲目地将它们全部转义。(这是线程后面的混淆)

如果希望能够使用部分或全部运算符,则需要使用更高级的转义。(我没有一个好的解决方案)


编辑:实际上让整个猪...

<?php

//Escapes all the Extended syntax, so can accept anything the user throws at us. 
function EscapeString ( $string ) {
   $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' );
   $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' );
   return str_replace ( $from, $to, $string );
}

if ($allow_full_extended_syntax) {
   $q = $_GET['q']; 
   // the user is responsible for providing valid query.
} elseif ($allow_partical_extended_syntax) {
   $q = InteligentEscape($_GET['q']); 
   //I don't have this function, it would need to be created. 
} else {
   $q = EscapeString($_GET['q']); 
   // escapes ALL extended syntax. NO operators allowed 
}

 $sphinxql_query = ".... MATCH('".mysqli_real_escape_string($sphinxql,$q)."') ";

然后听起来您希望将 $allow_full_extended_syntax 和 $allow_partical_extended_syntax 都设置为 false。这意味着没有运营商将工作,因为他们将被完全逃脱。

于 2015-08-14T16:02:52.347 回答
0

EscapeString 函数也需要转义 < 字符。另请参阅 PECL shpinx 中的 escapeString 函数以供参考。

于 2020-05-12T23:34:12.040 回答