如何使用PHP函数有效防止SQL注入?
- 内容介绍
- 文章标签
- 相关推荐
本文共计272个文字,预计阅读时间需要2分钟。
SQL注入或SQLi是常见的攻击网站的手法。以下是一些常见攻击手段及对应的防护代码示例:
攻击手段示例:
1.查询注入:通过在查询字符串中插入恶意SQL代码,以执行未经授权的操作。
2.插入注入:在插入数据时,通过输入恶意SQL代码,修改数据库结构或数据。
3.更新注入:在更新数据时,利用恶意SQL代码修改或删除数据。
防护代码示例:
phpfunction clean($input) { if (is_array($input)) { foreach ($input as $key=> $val) { $output[$key]=clean($val); // 递归调用clean函数 } } else { $output=$input; } return $output;}SQL 注入或者 SQLi 常见的攻击网站的手段,使用下面的代码可以帮助你防止SQL注入
function clean($input)
{
if (is_array($input))
{
foreach ($input as $key => $val)
{
$output[$key] = clean($val);
// $output[$key] = $this->clean($val);
}
}
else
{
$output = (string) $input;
// if magic quotes is on then use strip slashes
if (get_magic_quotes_gpc())
{
$output = stripslashes($output);
}
// $output = strip_tags($output);
$output = htmlentities($output, ENT_QUOTES, 'UTF-8');
}
// return the clean text
return $output;
}
用法:
<?php $text = "<script>alert(1)</script>"; $text = clean($text); echo $text; ?>
本文共计272个文字,预计阅读时间需要2分钟。
SQL注入或SQLi是常见的攻击网站的手法。以下是一些常见攻击手段及对应的防护代码示例:
攻击手段示例:
1.查询注入:通过在查询字符串中插入恶意SQL代码,以执行未经授权的操作。
2.插入注入:在插入数据时,通过输入恶意SQL代码,修改数据库结构或数据。
3.更新注入:在更新数据时,利用恶意SQL代码修改或删除数据。
防护代码示例:
phpfunction clean($input) { if (is_array($input)) { foreach ($input as $key=> $val) { $output[$key]=clean($val); // 递归调用clean函数 } } else { $output=$input; } return $output;}SQL 注入或者 SQLi 常见的攻击网站的手段,使用下面的代码可以帮助你防止SQL注入
function clean($input)
{
if (is_array($input))
{
foreach ($input as $key => $val)
{
$output[$key] = clean($val);
// $output[$key] = $this->clean($val);
}
}
else
{
$output = (string) $input;
// if magic quotes is on then use strip slashes
if (get_magic_quotes_gpc())
{
$output = stripslashes($output);
}
// $output = strip_tags($output);
$output = htmlentities($output, ENT_QUOTES, 'UTF-8');
}
// return the clean text
return $output;
}
用法:
<?php $text = "<script>alert(1)</script>"; $text = clean($text); echo $text; ?>

