日历

« 2008-07-25  
  12345
6789101112
13141516171819
20212223242526
2728293031  

RSS订阅

SQL防注入代码

2008-04-17 22:32:46 / 个人分类:代码

<?php
/**
* 防sql注入
* @author: zhuyubing@gmail.com
* */
/**
* reject sql inject
*/
if (!function_exists (quote))
{
function quote($var)
{
if (strlen($var))
{
$var=!get_magic_quotes_gpc() ? $var : stripslashes($var);
$var = str_replace("'","\'",$var);
}
return "'$var'";
}
}

if (!function_exists (hash_num)){
function hash_num($input)
{
$hash = 5381;

for ($i = 0; $i < strlen($str); $i++)
{
$c = ord($str{$i});
$hash = (($hash << 5) + $hash) + $c;
}
return $hash;
}
}
/**************** end *************************/
?>





<?php
/**
* 防sql测试代码
CREATE TABLE IF NOT EXISTS `tb` (
`id` int(10) unsigned NOT NULL auto_increment,
`age` tinyint(3) unsigned NOT NULL,
`name` char(100) NOT NULL,
`note` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
**/
include_once('common.php');
var_dump(hash_num('dddd'));

if(empty($_GET))
{
$_GET = array('age'=>'99','name'=>'a\'b\\\'c";','note'=>"a'b\'\nc#");
}

$age = (int)$_GET['age'];
$name = quote($_GET['name']);
$note = quote($_GET['note']);

$sql = "INSERT INTO `tb` ( `age`, `name`, `note`) VALUES
( $age, $name, $note)";

var_dump($sql);

?>

TAG: 代码

Open Toolbar