【发布时间】:2011-02-15 15:45:37
【问题描述】:
我正在努力保护我的网站,这样我就不会受到 sql 注入或 xss 的攻击。
这是我的代码:
//here's the form (abbreviated)
<form>
<label for="first_name" class="styled">First Name:</label>
<input type="text" id="first_name" name="first_name" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br />
//submit button etc
</form>
if (isset($_POST['submit'])) {
//gets rid of extra whitesapce and escapes
$first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
//check if $first_name is a string
if(!is_string($first_name)
{
echo "not string";
}
//then insert into the database.
.......
}
mysqli_real_escape_string:我知道这个函数会转义某些字母,例如\n \r,所以当数据输入到dbc时,它会在所有转义字母旁边都有'\'吗?
这个脚本是否足以阻止大多数 sql 注入?只是转义并检查数据是否为字符串。对于整数值(比如用户输入价格),我只是:
is_numeric()。我应该如何使用
htmlspecialchars?我应该只在回显和显示用户数据时使用它吗?还是在将数据插入数据库时也应该使用它?什么时候应该使用
strip_tags或htmlspecialchars?
所以有了所有这些功能:
if (isset($_POST['submit'])) {
//gets rid of extra whitesapce and escapes
$first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
//check if $first_name is a string
if(!is_string($first_name)
{
echo "not string";
}
//gets rid of any <,>,&
htmlspecialchars($first_name);
//strips any tags with the first name
strip_tags($first_name)
//then insert into the database.
.......
}
sql注入应该使用哪些函数,xss应该使用哪些函数?
用户何时可以对我插入 xss 脚本?什么时候有表格?
【问题讨论】:
-
我建议进行适当的表单验证,而不是仅仅清除用户提供的数据。
-
正确的表单验证是什么意思?
-
当我说正确的表单验证时,我主要想到一些 Web 框架中的示例,这些框架使用编程语言中构建的 html 表单的抽象,即创建一个类来表示一个表单,该表单将知道它具有哪些字段以及如何验证它们,返回清理后的数据,打印出 html 等。在您的示例中,您可以使用正则表达式('\w+')验证您的 $first_name,如果验证通过,您很确定您没有字符串中的任何不安全字符,如反斜杠等,否则会引发错误。
标签: php mysql security xss sql-injection