存储型XSS对用户的输入进行过滤的方式和反射型XSS相同,这里我们使用htmlspecialchars()
( 把预定义的字符 "<" (小于)和 ">" (大于)转换为 HTML 实体 )
htmlspecialchars和htmlentities的区别:
htmlspecialchars 只转义 & 、" 、' 、< 、> 这几个html代码
htmlentities 却会转化所有的html代码,连同里面的它无法识别的中文字符也会转化。
新建Xss_htmlspecialchars_Storage.php ,代码如下:
<span style="font-size:18px;"><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<html>
<head>
<title>XssStorage</title>
</head>
<body>
<h2>Message Board<h2>
<br>
<form action="Xss_htmlspecialchars_Storage.php" method="post">
Message:<textarea id='Mid' name="desc"></textarea>
<br>
<br>
Subuser:<input type="text" name="user"/4><br>
<br>
<input type="submit" value="submit" onclick='loction="XssStorage.php"'/>
</form>
<?php
if(isset($_POST['user'])&&isset($_POST['desc'])){
$log=fopen("sqlStorage.txt","a");
fwrite($log,htmlspecialchars($_POST['user'])."\r\n"); # 在此对用户输入数据$_POST['user']进行过滤
fwrite($log,htmlspecialchars($_POST['desc'])."\r\n"); # 在此对用户输入数据$_POST['desc']进行过滤
fclose($log);
}
if(file_exists("sqlStorage.txt"))
{
$read= fopen("sqlStorage.txt",'r');
while(!feof($read))
{
echo fgets($read)."</br>";
}
fclose($read);
}
?>
</body>
</html></span>
当我们在Message中输入<script>alert('xss')</script>
:
可以看到页面并没有弹窗,查看网页html代码:
可以看到htmlspecialchars()函数对用户输入的<>
做了转义处理。