了解常见的PHP应用程序安全威胁,可以确保你的PHP应用程序不受攻击。因此,本文将列出 6个常见的 PHP 安全性攻击,欢迎大家来阅读和学习。?
01
$username?=?$_POST['username'];
02
$query?=?"select * from auth where username = '".$username."'";
03
functions">echo?$query;
04
$db?=?new?mysqli('localhost',?'demo', ‘demo', ‘demodemo');
05
$result?=?$db->query($query);
06
if?($result?&&?$result->num_rows) {
07
????echo?"<br />Logged in successfully";
08
}?else?{
09
????echo?"<br />Login failed";
10
}
上面的代码,在第一行没有过滤或转义用户输入的值($_POST['username'])。因此查询可能会失败,甚至会损坏数据库,这要看$username是否包含变换你的SQL语句到别的东西上。?
防止SQL注入?
选项:?
使用准备好的预处理语句?
?
01
$query?=?'select name, district from city where countrycode=?';
02
if?($stmt?=?$db->prepare($query) )
03
{
04
????$countrycode?=?'hk';
05
????$stmt->bind_param("s",?$countrycode);?
06
????$stmt->execute();
07
????$stmt->bind_result($name,?$district);
08
????while?(?$stmt?($stmt->fetch() ){
09
????????echo?$name.', '.$district;
10
????????echo?'<br />';
11
????}
12
????$stmt->close();
13
}
01
<?php
02
if?(file_exists('comments')) {
03
????$comments?= get_saved_contents_from_file('comments');
04
}?else?{
05
????$comments?=?'';
06
}
07
08
if?(isset($_POST['comment'])) {
09
????$comments?.=?'<br />'?.?$_POST['comment'];
10
????save_contents_to_file('comments',?$comments);
11
}
12
>
输出内容给(另一个)用户?
1
<form action='xss.php'?method='POST'>
2
Enter your comments here: <br />
3
<textarea name='comment'></textarea> <br />
4
<input type='submit'?value='Post comment'?/>
5
</form><hr /><br />
6
7
<?php?echo?$comments; ?>
将会发生什么事??
防止XSS攻击?
为了防止XSS攻击,使用PHP的htmlentities()函数过滤再输出到浏览器。htmlentities()的基本用法很简单,但也有许多高级的控制,请参阅?XSS速查表。?
?
1
<img?src='http://example.com/single_click_to_buy.php?user_id=123&item=12345'>
防止跨站点请求伪造?
一般来说,确保用户来自你的表单,并且匹配每一个你发送出去的表单。有两点一定要记住:?
01
<form>Choose theme:
02
????<select name = theme>
03
????????<option value = blue>Blue</option>
04
????????<option value = green>Green</option>
05
????????<option value = red>Red</option>
06
????</select>
07
????<input type = submit>
08
</form>
09
<?php
10
????if($theme) {
11
????????require($theme.'.txt');
12
????}
13
?>
在上面的例子中,通过传递用户输入的一个文件名或文件名的一部分,来包含以"http://"开头的文件。?
防止代码注入?
??
其他的一般原则?
1. 不要依赖服务器配置来保护你的应用,特别是当你的web服务器/ PHP是由你的ISP管理,或者当你的网站可能迁移/部署到别处,未来再从别处迁移/部署在到其他地方。请在网站代码中嵌入带有安全意识的检查/逻辑(HTML、JavaScript、PHP,等等)。 ?
2. 设计服务器端的安全脚本:?
—例如,使用单行执行 - 单点身份验证和数据清理 ?
—例如,在所有的安全敏感页面嵌入一个PHP函数/文件,用来处理所有登录/安全性逻辑检查?
3. 确保你的代码更新,并打上最新补丁。?