在插入数据库中的数据时,你必须要很小心SQL注入和其他试图插入恶意数据到DB中。下面的函数可能是最完整和最有效的方式在将数据保存至数据库之前,对其进行”消毒“。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
function cleanInput( $input ) { $search = array ( '@<script[^>]*?>.*?</script>@si' , // Strip out javascript '@<[\/\!]*?[^<>]*?>@si' , // Strip out HTML tags '@<style[^>]*?>.*?</style>@siU' , // Strip style tags properly '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments ); $output = preg_replace( $search , '' , $input ); return $output ; } ?> <?php function sanitize( $input ) { if ( is_array ( $input )) { foreach ( $input as $var => $val ) { $output [ $var ] = sanitize( $val ); } } else { if (get_magic_quotes_gpc()) { $input = stripslashes ( $input ); } $input = cleanInput( $input ); $output = mysql_real_escape_string( $input ); } return $output ; } |
下面是一些使用的例子:
1
2
3
4
5
6
7
8
9
|
<?php $bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!" ; $good_string = sanitize( $bad_string ); // $good_string returns "Hi! It\'s a good day!" // Also use for getting POST/GET variables $_POST = sanitize( $_POST ); $_GET = sanitize( $_GET ); ?> |