PHP+Mysql防止SQL注入的3种方法:
mysql_real_escape_string -- 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集 !
使用方法如下:
$sql = "select count(*) as ctr from users where username ='".mysql_real_escape_string($username)."' and password='". mysql_real_escape_string($pw)."' limit 1";
使用 mysql_real_escape_string() 作为用户输入的包装器,就可以避免用户输入中的任何恶意 SQL 注入。
打开magic_quotes_gpc来防止SQL注入
php.ini中有一个设置:magic_quotes_gpc = Off
这个默认是关闭的,如果它打开后将自动把用户提交对sql的查询进行转换,
比如把 ' 转为 \'等,对于防止sql注射有重大作用。
如果magic_quotes_gpc=Off,则使用addslashes()函数
/**
* 防止sql注入自定义方法一
* author: xiaochuan
* @param: mixed $value 参数值
*/
function check_param($value=null) {
# select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile
$str = 'select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile';
if(!$value) {
exit('没有参数!');
}elseif(eregi($str, $value)) {
exit('参数非法!');
}
return true;
}
/**
* 防止sql注入自定义方法二
* author: xiaochuan
* @param: mixed $value 参数值
*/
function str_check( $value ) {
if(!get_magic_quotes_gpc()) {
// 进行过滤
$value = addslashes($value);
}
$value = str_replace("_", "\_", $value);
$value = str_replace("%", "\%", $value);
return $value;
}
/**
* 防止sql注入自定义方法三
* author: xiaochuan
* @param: mixed $value 参数值
*/
function post_check($value) {
if(!get_magic_quotes_gpc()) {
// 进行过滤
$value = addslashes($value);
}
$value = str_replace("_", "\_", $value);
$value = str_replace("%", "\%", $value);
$value = nl2br($value);
$value = htmlspecialchars($value);
return $value;
}转载请注明来源地址:小川编程 » https://www.youhutong.com/index.php/article/index/109.html
1、本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,下载后请24小时内删除。
2、本站所有内容均不能保证其完整性,不能接受请勿购买或下载,如需完整程序,请去其官方购买正版使用
3、本站联系方式Email:admin@youhutong.com ,收到邮件会第一时间处理。
4、如侵犯到任何版权问题,请立即告知本站(立即在线告知),本站将及时删除并致以最深的歉意

