国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

682 lines
23KB

  1. <?php
  2. if (!defined('DEDEINC')) exit('dedebiz');
  3. /**
  4. * 数据库类
  5. * 说明:系统底层数据库核心类
  6. * 调用这个类前,请先设定这些外部变量
  7. * $GLOBALS['cfg_dbhost'];
  8. * $GLOBALS['cfg_dbuser'];
  9. * $GLOBALS['cfg_dbpwd'];
  10. * $GLOBALS['cfg_dbname'];
  11. * $GLOBALS['cfg_dbprefix'];
  12. *
  13. * @version $Id: dedesqli.class.php 1 15:00 2011-1-21 tianya $
  14. * @package DedeBIZ.Libraries
  15. * @copyright Copyright (c) 2022, DedeBIZ.COM
  16. * @license https://www.dedebiz.com/license
  17. * @link https://www.dedebiz.com
  18. */
  19. @set_time_limit(0);
  20. // 在工程所有文件中均不需要单独初始化这个类,可直接用 $dsql 或 $db 进行操作
  21. // 为了防止错误,操作完后不必关闭数据库
  22. if (!function_exists("mysqli_init")) {
  23. echo "DedeBIZ提示:尚未发现开启mysqli模块,请在php.ini中启用`extension=mysqli`。";
  24. exit;
  25. }
  26. $dsql = $dsqli = $db = new DedeSqli(FALSE);
  27. /**
  28. * Dede MySQLi数据库类
  29. *
  30. * @package DedeSqli
  31. * @subpackage DedeBIZ.Libraries
  32. * @link https://www.dedebiz.com
  33. */
  34. if (!defined('MYSQL_BOTH')) {
  35. define('MYSQL_BOTH', MYSQLI_BOTH);
  36. }
  37. if (!defined('MYSQL_ASSOC')) {
  38. define('MYSQL_ASSOC', MYSQLI_ASSOC);
  39. }
  40. class DedeSqli
  41. {
  42. var $linkID;
  43. var $dbHost;
  44. var $dbUser;
  45. var $dbPwd;
  46. var $dbName;
  47. var $dbPrefix;
  48. var $result;
  49. var $queryString;
  50. var $parameters;
  51. var $isClose;
  52. var $safeCheck;
  53. var $showError = false;
  54. var $recordLog = false; //记录日志到data/mysqli_record_log.inc便于进行调试
  55. var $isInit = false;
  56. var $pconnect = false;
  57. //用外部定义的变量初始类,并连接数据库
  58. function __construct($pconnect = FALSE, $nconnect = FALSE)
  59. {
  60. $this->isClose = FALSE;
  61. $this->safeCheck = TRUE;
  62. $this->pconnect = $pconnect;
  63. if ($nconnect) {
  64. $this->Init($pconnect);
  65. }
  66. }
  67. function DedeSql($pconnect = FALSE, $nconnect = TRUE)
  68. {
  69. $this->__construct($pconnect, $nconnect);
  70. }
  71. function Init($pconnect = FALSE)
  72. {
  73. $this->linkID = 0;
  74. //$this->queryString = '';
  75. //$this->parameters = Array();
  76. $this->dbHost = $GLOBALS['cfg_dbhost'];
  77. $this->dbUser = $GLOBALS['cfg_dbuser'];
  78. $this->dbPwd = $GLOBALS['cfg_dbpwd'];
  79. $this->dbName = $GLOBALS['cfg_dbname'];
  80. $this->dbPrefix = $GLOBALS['cfg_dbprefix'];
  81. $this->result["me"] = 0;
  82. $this->Open($pconnect);
  83. }
  84. //用指定参数初始数据库信息
  85. function SetSource($host, $username, $pwd, $dbname, $dbprefix = "dede_")
  86. {
  87. $this->dbHost = $host;
  88. $this->dbUser = $username;
  89. $this->dbPwd = $pwd;
  90. $this->dbName = $dbname;
  91. $this->dbPrefix = $dbprefix;
  92. $this->result["me"] = 0;
  93. }
  94. function SelectDB($dbname)
  95. {
  96. mysqli_select_db($this->linkID, $dbname);
  97. }
  98. //设置SQL里的参数
  99. function SetParameter($key, $value)
  100. {
  101. $this->parameters[$key] = $value;
  102. }
  103. //连接数据库
  104. function Open($pconnect = FALSE)
  105. {
  106. global $dsqli;
  107. //连接数据库
  108. if ($dsqli && !$dsqli->isClose && $dsqli->isInit) {
  109. $this->linkID = $dsqli->linkID;
  110. } else {
  111. $i = 0;
  112. @list($dbhost, $dbport) = explode(':', $this->dbHost);
  113. !$dbport && $dbport = 3306;
  114. $this->linkID = mysqli_init();
  115. mysqli_real_connect($this->linkID, $dbhost, $this->dbUser, $this->dbPwd, false, $dbport);
  116. mysqli_errno($this->linkID) != 0 && $this->DisplayError('DedeBIZ错误警告:链接('.$this->pconnect.') 到MySQL发生错误');
  117. //复制一个对象副本
  118. CopySQLiPoint($this);
  119. }
  120. //处理错误,成功连接则选择数据库
  121. if (!$this->linkID) {
  122. $this->DisplayError("DedeBIZ错误警告:<span style='color:#dc3545'>连接数据库失败,可能数据库密码不对或数据库服务器出错</span>");
  123. exit();
  124. }
  125. $this->isInit = TRUE;
  126. $serverinfo = mysqli_get_server_info($this->linkID);
  127. if (version_compare($serverinfo, '4.1', ">=") && $GLOBALS['cfg_db_language']) {
  128. mysqli_query($this->linkID, "SET character_set_connection=".$GLOBALS['cfg_db_language'].",character_set_results=".$GLOBALS['cfg_db_language'].",character_set_client=binary");
  129. }
  130. if ($serverinfo > '5.0') {
  131. mysqli_query($this->linkID, "SET sql_mode=''");
  132. }
  133. if ($this->dbName && !@mysqli_select_db($this->linkID, $this->dbName)) {
  134. $this->DisplayError('无法使用数据库');
  135. }
  136. return TRUE;
  137. }
  138. //为了防止采集等需要较长运行时间的程序超时,在运行这类程序时设置系统等待和交互时间
  139. function SetLongLink()
  140. {
  141. if ($this->linkID) {
  142. @mysqli_query($this->linkID, "SET interactive_timeout=3600, wait_timeout=3600 ;");
  143. }
  144. }
  145. //获得错误描述
  146. function GetError()
  147. {
  148. $str = mysqli_error($this->linkID);
  149. return $str;
  150. }
  151. //关闭数据库
  152. //mysql能自动管理非持久连接的连接池
  153. //实际上关闭并无意义并且容易出错,所以取消这函数
  154. function Close($isok = FALSE)
  155. {
  156. $this->FreeResultAll();
  157. if ($isok) {
  158. @mysqli_close($this->linkID);
  159. $this->isClose = TRUE;
  160. $GLOBALS['dsql'] = NULL;
  161. }
  162. }
  163. //定期清理死连接
  164. function ClearErrLink()
  165. {
  166. }
  167. //关闭指定的数据库连接
  168. function CloseLink($dblink)
  169. {
  170. @mysqli_close($dblink);
  171. }
  172. function Esc($_str)
  173. {
  174. if (version_compare(phpversion(), '4.3.0', '>=')) {
  175. return @mysqli_real_escape_string($this->linkID, $_str);
  176. } else {
  177. return @mysqli_escape_string($this->linkID, $_str);
  178. }
  179. }
  180. //执行一个不返回结果的SQL语句,如update,delete,insert等
  181. function ExecuteNoneQuery($sql = '')
  182. {
  183. global $dsqli;
  184. if (!$dsqli->isInit) {
  185. $this->Init($this->pconnect);
  186. }
  187. if ($dsqli->isClose) {
  188. $this->Open(FALSE);
  189. $dsqli->isClose = FALSE;
  190. }
  191. if (!empty($sql)) {
  192. $this->SetQuery($sql);
  193. } else {
  194. return FALSE;
  195. }
  196. if (is_array($this->parameters)) {
  197. foreach ($this->parameters as $key => $value) {
  198. $this->queryString = str_replace("@".$key, "'$value'", $this->queryString);
  199. }
  200. }
  201. //SQL语句安全检查
  202. if ($this->safeCheck) CheckSql($this->queryString, 'update');
  203. $t1 = ExecTime();
  204. $rs = mysqli_query($this->linkID, $this->queryString);
  205. //查询性能测试
  206. if ($this->recordLog) {
  207. $queryTime = ExecTime() - $t1;
  208. $this->RecordLog($queryTime);
  209. }
  210. if (DEBUG_LEVEL === TRUE) {
  211. $queryTime = ExecTime() - $t1;
  212. if (PHP_SAPI === 'cli') {
  213. echo "执行SQL:".$this->queryString.",执行时间:{$queryTime}\r\n";
  214. } else {
  215. echo "<div style='width:98%;margin:1rem auto;color: #155724;background-color: #d4edda;border-color: #c3e6cb;position: relative;padding: .75rem 1.25rem;border: 1px solid transparent;border-radius: .25rem;'>执行SQL:".$this->queryString.",执行时间:<b>{$queryTime}</b></div>\r\n";
  216. }
  217. }
  218. return $rs;
  219. }
  220. //执行一个返回影响记录条数的SQL语句,如update,delete,insert等
  221. function ExecuteNoneQuery2($sql = '')
  222. {
  223. global $dsqli;
  224. if (!$dsqli->isInit) {
  225. $this->Init($this->pconnect);
  226. }
  227. if ($dsqli->isClose) {
  228. $this->Open(FALSE);
  229. $dsqli->isClose = FALSE;
  230. }
  231. if (!empty($sql)) {
  232. $this->SetQuery($sql);
  233. }
  234. if (is_array($this->parameters)) {
  235. foreach ($this->parameters as $key => $value) {
  236. $this->queryString = str_replace("@".$key, "'$value'", $this->queryString);
  237. }
  238. }
  239. $t1 = ExecTime();
  240. mysqli_query($this->linkID, $this->queryString);
  241. //查询性能测试
  242. if ($this->recordLog) {
  243. $queryTime = ExecTime() - $t1;
  244. $this->RecordLog($queryTime);
  245. //echo $this->queryString."--{$queryTime}<hr />\r\n";
  246. }
  247. if (DEBUG_LEVEL === TRUE) {
  248. $queryTime = ExecTime() - $t1;
  249. if (PHP_SAPI === 'cli') {
  250. echo "执行SQL:".$this->queryString.",执行时间:{$queryTime}\r\n";
  251. } else {
  252. echo "<div style='width:98%;margin:1rem auto;color: #155724;background-color: #d4edda;border-color: #c3e6cb;position: relative;padding: .75rem 1.25rem;border: 1px solid transparent;border-radius: .25rem;'>执行SQL:".$this->queryString.",执行时间:<b>{$queryTime}</b></div>\r\n";
  253. }
  254. }
  255. return mysqli_affected_rows($this->linkID);
  256. }
  257. function ExecNoneQuery($sql = '')
  258. {
  259. return $this->ExecuteNoneQuery($sql);
  260. }
  261. function GetFetchRow($id = 'me')
  262. {
  263. return @mysqli_fetch_row($this->result[$id]);
  264. }
  265. function GetAffectedRows()
  266. {
  267. return mysqli_affected_rows($this->linkID);
  268. }
  269. //执行一个带返回结果的SQL语句,如SELECT,SHOW等
  270. function Execute($id = "me", $sql = '')
  271. {
  272. global $dsqli;
  273. if (!$dsqli->isInit) {
  274. $this->Init($this->pconnect);
  275. }
  276. if ($dsqli->isClose) {
  277. $this->Open(FALSE);
  278. $dsqli->isClose = FALSE;
  279. }
  280. if (!empty($sql)) {
  281. $this->SetQuery($sql);
  282. }
  283. //SQL语句安全检查
  284. if ($this->safeCheck) {
  285. CheckSql($this->queryString);
  286. }
  287. $t1 = ExecTime();
  288. //var_dump($this->queryString);
  289. $this->result[$id] = mysqli_query($this->linkID, $this->queryString);
  290. //var_dump(mysql_error());
  291. //查询性能测试
  292. if ($this->recordLog) {
  293. $queryTime = ExecTime() - $t1;
  294. $this->RecordLog($queryTime);
  295. //echo $this->queryString."--{$queryTime}<hr />\r\n";
  296. }
  297. if (DEBUG_LEVEL === TRUE) {
  298. $queryTime = ExecTime() - $t1;
  299. if (PHP_SAPI === 'cli') {
  300. echo "执行SQL:".$this->queryString.",执行时间:{$queryTime}\r\n";
  301. } else {
  302. echo "<div style='width:98%;margin:1rem auto;color: #155724;background-color: #d4edda;border-color: #c3e6cb;position: relative;padding: .75rem 1.25rem;border: 1px solid transparent;border-radius: .25rem;'>执行SQL:".$this->queryString.",执行时间:<b>{$queryTime}</b></div>\r\n";
  303. }
  304. }
  305. if ($this->result[$id] === FALSE) {
  306. $this->DisplayError(mysqli_error($this->linkID)." <br />Error sql: <span style='color:#dc3545'>".$this->queryString."</span>");
  307. }
  308. }
  309. function Query($id = "me", $sql = '')
  310. {
  311. $this->Execute($id, $sql);
  312. }
  313. //执行一个SQL语句,返回前一条记录或仅返回一条记录
  314. function GetOne($sql = '', $acctype = MYSQLI_ASSOC)
  315. {
  316. global $dsqli;
  317. //$t1 = ExecTime();
  318. if (!$dsqli->isInit) {
  319. $this->Init($this->pconnect);
  320. }
  321. //echo ExecTime() - $t1;
  322. if ($dsqli->isClose) {
  323. $this->Open(FALSE);
  324. $dsqli->isClose = FALSE;
  325. }
  326. if (!empty($sql)) {
  327. if (!preg_match("/LIMIT/i", $sql)) $this->SetQuery(preg_replace("/[,;]$/i", '', trim($sql))." LIMIT 0,1;");
  328. else $this->SetQuery($sql);
  329. }
  330. $this->Execute("one");
  331. $arr = $this->GetArray("one", $acctype);
  332. if (!is_array($arr)) {
  333. return '';
  334. } else {
  335. @mysqli_free_result($this->result["one"]);
  336. return ($arr);
  337. }
  338. }
  339. //执行一个不与任何表名有关的SQL语句,Create等
  340. function ExecuteSafeQuery($sql, $id = "me")
  341. {
  342. global $dsqli;
  343. if (!$dsqli->isInit) {
  344. $this->Init($this->pconnect);
  345. }
  346. if ($dsqli->isClose) {
  347. $this->Open(FALSE);
  348. $dsqli->isClose = FALSE;
  349. }
  350. $this->result[$id] = @mysqli_query($sql, $this->linkID);
  351. }
  352. //返回当前的一条记录并把游标移向下一记录
  353. //MYSQLI_ASSOC、MYSQLI_NUM、MYSQLI_BOTH
  354. function GetArray($id = "me", $acctype = MYSQLI_ASSOC)
  355. {
  356. //var_dump($this->result);
  357. if ($this->result[$id] === 0) {
  358. return FALSE;
  359. } else {
  360. return @mysqli_fetch_array($this->result[$id], $acctype);
  361. }
  362. }
  363. function GetObject($id = "me")
  364. {
  365. if ($this->result[$id] === 0) {
  366. return FALSE;
  367. } else {
  368. return mysqli_fetch_object($this->result[$id]);
  369. }
  370. }
  371. //检测是否存在某数据表
  372. function IsTable($tbname)
  373. {
  374. global $dsqli;
  375. if (!$dsqli->isInit) {
  376. $this->Init($this->pconnect);
  377. }
  378. $prefix = "#@__";
  379. $tbname = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $tbname);
  380. if (mysqli_num_rows(@mysqli_query($this->linkID, "SHOW TABLES LIKE '".$tbname."'"))) {
  381. return TRUE;
  382. }
  383. return FALSE;
  384. }
  385. //获得MySql的版本号
  386. function GetVersion($isformat = TRUE)
  387. {
  388. global $dsqli;
  389. if (!$dsqli->isInit) {
  390. $this->Init($this->pconnect);
  391. }
  392. if ($dsqli->isClose) {
  393. $this->Open(FALSE);
  394. $dsqli->isClose = FALSE;
  395. }
  396. $rs = mysqli_query($this->linkID, "SELECT VERSION();");
  397. $row = mysqli_fetch_array($rs);
  398. $mysql_version = $row[0];
  399. mysqli_free_result($rs);
  400. if ($isformat) {
  401. $mysql_versions = explode(".", trim($mysql_version));
  402. $mysql_version = number_format($mysql_versions[0].".".$mysql_versions[1], 2);
  403. }
  404. return $mysql_version;
  405. }
  406. //获取特定表的信息
  407. function GetTableFields($tbname, $id = "me")
  408. {
  409. global $dsqli;
  410. if (!$dsqli->isInit) {
  411. $this->Init($this->pconnect);
  412. }
  413. $prefix = "#@__";
  414. $tbname = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $tbname);
  415. $query = "SELECT * FROM {$tbname} LIMIT 0,1";
  416. $this->result[$id] = mysqli_query($this->linkID, $query);
  417. }
  418. //获取字段详细信息
  419. function GetFieldObject($id = "me")
  420. {
  421. return mysqli_fetch_field($this->result[$id]);
  422. }
  423. //获得查询的总记录数
  424. function GetTotalRow($id = "me")
  425. {
  426. if ($this->result[$id] === 0) {
  427. return -1;
  428. } else {
  429. return @mysqli_num_rows($this->result[$id]);
  430. }
  431. }
  432. //获取上一步INSERT操作产生的ID
  433. function GetLastID()
  434. {
  435. //如果 AUTO_INCREMENT 的列的类型是 BIGINT,则 mysqli_insert_id() 返回的值将不正确。
  436. //可以在 SQL 查询中用 MySQL 内部的 SQL 函数 LAST_INSERT_ID() 来替代。
  437. //$rs = mysqli_query($this->linkID, "Select LAST_INSERT_ID() as lid");
  438. //$row = mysqli_fetch_array($rs);
  439. //return $row["lid"];
  440. return mysqli_insert_id($this->linkID);
  441. }
  442. //释放记录集占用的资源
  443. function FreeResult($id = "me")
  444. {
  445. @mysqli_free_result($this->result[$id]);
  446. }
  447. function FreeResultAll()
  448. {
  449. if (!is_array($this->result)) {
  450. return '';
  451. }
  452. foreach ($this->result as $kk => $vv) {
  453. if ($vv) {
  454. @mysqli_free_result($vv);
  455. }
  456. }
  457. }
  458. //设置SQL语句,会自动把SQL语句里的#@__替换为$this->dbPrefix(在配置文件中为$cfg_dbprefix)
  459. function SetQuery($sql)
  460. {
  461. $prefix = "#@__";
  462. $sql = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $sql);
  463. $this->queryString = $sql;
  464. }
  465. function SetSql($sql)
  466. {
  467. $this->SetQuery($sql);
  468. }
  469. function RecordLog($runtime = 0)
  470. {
  471. $RecordLogFile = dirname(__FILE__).'/../data/mysqli_record_log.inc';
  472. $url = $this->GetCurUrl();
  473. $savemsg = <<<EOT
  474. ------------------------------------------
  475. SQL:{$this->queryString}
  476. Page:$url
  477. Runtime:$runtime
  478. EOT;
  479. $fp = @fopen($RecordLogFile, 'a');
  480. @fwrite($fp, $savemsg);
  481. @fclose($fp);
  482. }
  483. //显示数据链接错误信息
  484. function DisplayError($msg)
  485. {
  486. $errorTrackFile = dirname(__FILE__).'/../data/mysqli_error_trace.inc';
  487. if (file_exists(dirname(__FILE__).'/../data/mysqli_error_trace.php')) {
  488. @unlink(dirname(__FILE__).'/../data/mysqli_error_trace.php');
  489. }
  490. if ($this->showError) {
  491. $emsg = '';
  492. $emsg .= "<div><h3>DedeBIZ Error Warning!</h3>\r\n";
  493. $emsg .= "<div><a href='https://www.dedebiz.com' target='_blank' style='color:#dc3545'>Technical Support: https://www.dedebiz.com</a></div>";
  494. $emsg .= "<div style='line-helght:160%;font-size:14px;color:green'>\r\n";
  495. $emsg .= "<div style='color:blue'><br />Error page: <span style='color:#dc3545'>".$this->GetCurUrl()."</span></div>\r\n";
  496. $emsg .= "<div>Error infos: {$msg}</div>\r\n";
  497. $emsg .= "<br /></div></div>\r\n";
  498. echo $emsg;
  499. }
  500. $savemsg = 'Page: '.$this->GetCurUrl()."\r\nError: ".$msg."\r\nTime".date('Y-m-d H:i:s');
  501. //保存MySql错误日志
  502. $fp = @fopen($errorTrackFile, 'a');
  503. @fwrite($fp, '<'.'?php exit();'."\r\n/*\r\n{$savemsg}\r\n*/\r\n?".">\r\n");
  504. @fclose($fp);
  505. }
  506. //获得当前的脚本网址
  507. function GetCurUrl()
  508. {
  509. if (!empty($_SERVER["REQUEST_URI"])) {
  510. $scriptName = $_SERVER["REQUEST_URI"];
  511. $nowurl = $scriptName;
  512. } else {
  513. $scriptName = $_SERVER["PHP_SELF"];
  514. if (empty($_SERVER["QUERY_STRING"])) {
  515. $nowurl = $scriptName;
  516. } else {
  517. $nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];
  518. }
  519. }
  520. return $nowurl;
  521. }
  522. }
  523. //复制一个对象副本
  524. function CopySQLiPoint(&$ndsql)
  525. {
  526. $GLOBALS['dsqli'] = $ndsql;
  527. }
  528. //SQL语句过滤程序,由80sec提供,这里作了适当的修改
  529. if (!function_exists('CheckSql')) {
  530. function CheckSql($db_string, $querytype = 'select')
  531. {
  532. global $cfg_cookie_encode;
  533. $clean = '';
  534. $error = '';
  535. $old_pos = 0;
  536. $pos = -1;
  537. $log_file = DEDEINC.'/../data/'.md5($cfg_cookie_encode).'_safe.txt';
  538. $userIP = GetIP();
  539. $getUrl = GetCurUrl();
  540. //如果是普通查询语句,直接过滤一些特殊语法
  541. if ($querytype == 'select') {
  542. $notallow1 = "[^0-9a-z@\._-]{1,}(union|sleep|benchmark|load_file|outfile)[^0-9a-z@\.-]{1,}";
  543. //$notallow2 = "--|/\*";
  544. if (preg_match("/".$notallow1."/i", $db_string)) {
  545. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||SelectBreak\r\n");
  546. exit("<span>Safe Alert: Request Error step 1 !</span>");
  547. }
  548. }
  549. //完整的SQL检查
  550. while (TRUE) {
  551. $pos = strpos($db_string, '\'', $pos + 1);
  552. if ($pos === FALSE) {
  553. break;
  554. }
  555. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  556. while (TRUE) {
  557. $pos1 = strpos($db_string, '\'', $pos + 1);
  558. $pos2 = strpos($db_string, '\\', $pos + 1);
  559. if ($pos1 === FALSE) {
  560. break;
  561. } elseif ($pos2 == FALSE || $pos2 > $pos1) {
  562. $pos = $pos1;
  563. break;
  564. }
  565. $pos = $pos2 + 1;
  566. }
  567. $clean .= '$s$';
  568. $old_pos = $pos + 1;
  569. }
  570. $clean .= substr($db_string, $old_pos);
  571. $clean = trim(strtolower(preg_replace(array('~\s+~s'), array(' '), $clean)));
  572. if (
  573. strpos($clean, '@') !== FALSE or strpos($clean, 'char(') !== FALSE or strpos($clean, '"') !== FALSE
  574. or strpos($clean, '$s$$s$') !== FALSE
  575. ) {
  576. $fail = TRUE;
  577. if (preg_match("#^create table#i", $clean)) $fail = FALSE;
  578. $error = "unusual character";
  579. }
  580. //老版本的Mysql并不支持union,常用的程序里也不使用union,但是一些黑客使用它,所以检查它
  581. if (strpos($clean, 'union') !== FALSE && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0) {
  582. $fail = TRUE;
  583. $error = "union detect";
  584. }
  585. //发布版本的程序可能比较少包括--,#这样的注释,但是黑客经常使用它们
  586. elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== FALSE || strpos($clean, '#') !== FALSE) {
  587. $fail = TRUE;
  588. $error = "comment detect";
  589. }
  590. //这些函数不会被使用,但是黑客会用它来操作文件,down掉数据库
  591. elseif (strpos($clean, 'sleep') !== FALSE && preg_match('~(^|[^a-z])sleep($|[^[a-z])~s', $clean) != 0) {
  592. $fail = TRUE;
  593. $error = "slown down detect";
  594. } elseif (strpos($clean, 'benchmark') !== FALSE && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) {
  595. $fail = TRUE;
  596. $error = "slown down detect";
  597. } elseif (strpos($clean, 'load_file') !== FALSE && preg_match('~(^|[^a-z])load_file($|[^[a-z])~s', $clean) != 0) {
  598. $fail = TRUE;
  599. $error = "file fun detect";
  600. } elseif (strpos($clean, 'into outfile') !== FALSE && preg_match('~(^|[^a-z])into\s+outfile($|[^[a-z])~s', $clean) != 0) {
  601. $fail = TRUE;
  602. $error = "file fun detect";
  603. }
  604. //老版本的MYSQL不支持子查询,我们的程序里可能也用得少,但是黑客可以使用它来查询数据库敏感信息
  605. elseif (preg_match('~\([^)]*?select~s', $clean) != 0) {
  606. $fail = TRUE;
  607. $error = "sub select detect";
  608. }
  609. if (!empty($fail)) {
  610. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||$error\r\n");
  611. exit("<span>Safe Alert: Request Error step 2!</span>");
  612. } else {
  613. return $db_string;
  614. }
  615. }
  616. }