我正在尝试保护我的网站,以免受到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 攻击?当存在表单时吗?