Sphinx-如何转义SphinxQL的用户输入?

问题描述 投票:0回答:2

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

但是当我在搜索查询中输入/输入一些特殊字符时,搜索文档完成并抛出错误。

例如我搜索的关键字:

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."') ";
?>

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

php sphinx sphinxql
2个回答
4
投票

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

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

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

...但您may还要,请转义扩展语法。

[在狮身人面像论坛中的该主题中查看第一篇三篇文章(之后它会引起误解)http://sphinxsearch.com/forum/view.html?id=13619

一个简单的解决方案。

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


但是,这也意味着您不能使用any搜索运算符-因为它会盲目地将它们全部转义。 (这是稍后在线程中造成的混乱)

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


编辑:小心翼翼地放开整只猪...

<?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。这意味着没有操作员可以工作,因为他们将完全逃脱。


0
投票

EscapeString函数也需要转义

© www.soinside.com 2019 - 2024. All rights reserved.