您的位置:首页 > 编程语言 > PHP开发

php防止sql注入的自定义函数

2016-03-31 20:33 477 查看
1.函数的构建

function inject_check($sql_str)
{

returneregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile',$sql_str); //
进行过滤

}

function verify_id($id=null)
{

if (!$id)
{ exit('没有提交参数!'); } //
是否为空判断

elseif (inject_check($id))
{ exit('提交的参数非法!'); } //
注射判断

elseif (!is_numeric($id))
{ exit('提交的参数非法!'); } //
数字判断

$id = intval($id); //
整型化

return $id;

}

function str_check( $str )
{

if (!get_magic_quotes_gpc()) { //
判断magic_quotes_gpc是否打开

$str = addslashes($str); //
进行过滤

}

$str = str_replace("_", "\_", $str); //
把 '_'过滤掉

$str = str_replace("%", "\%", $str); //
把 '%'过滤掉

return $str;

}

function post_check($post)
{

if (!get_magic_quotes_gpc()) { //
判断magic_quotes_gpc是否为打开

$post = addslashes($post); //
进行magic_quotes_gpc没有打开的情况对提交数据的过滤

}

$post = str_replace("_", "\_", $post); //
把 '_'过滤掉

$post = str_replace("%", "\%", $post); //
把 '%'过滤掉

$post = nl2br($post); //
回车转换

$post = htmlspecialchars($post); //
html标记转换

return $post;

}

2.函数的使用实例

<?php

if (inject_check($_GET['id']))

{

exit('你提交的数据非法,请检查后重新提交!');

}

else

{

$id = $_GET['id'];

//处理数据………………

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: