Home >Backend Development >PHP Tutorial >php安全简析
第一章 简介
1> 原则
深度防范
最小权限
简单就是美
暴露最小化
2>方法
平衡风险与可用性
跟踪数据
过滤输入
输出转义
//****防止表单提交骗术
session_start();
$_SESSION['token'] = md5(uniqid(mt_rand(), true));
//*****初始化一个用于保存过滤数据数组。
$clean = array();
if(ctype_alpha($_POST['name'])){
$clean['name'] = $_POST['name'];
}else{
//错误
}
//****避免跨站点脚本
/*使用真确的字符编码*/
header('Content-Type:text/heml; charset=UTF-8');
/*为保存转义后的数据初始化一个数组*/
$html = array();
$html['username'] = htmlentities($clean['username'], ENT_QUOTES,'UTF-8');
//****避免SQL注入
/*使用PDO之类的数据库来针对你的数据库进行适当的转义*/
$db = new PDO('mysql:host=localhost;dbname=users',$_SERVER['DB_USER'],$_SERVER['DB_PASSWORD']);
$statement = $db->prepare("INSERT INTO user (username, password) VALUES (:username, :password)");
$statement->bindParam(':username',$clean['username']);
$statement->bindParam(':password',$clean['password']);
$statement->execute();
$db = NULL;
安全的 PHP 表单处理代码
$okay = 0; $username = $_POST['user']; $pw = $_POST['pw']; $sql = "select count(*) as ctr from users where username='".mysql_real_escape_string($username)."' and password='". mysql_real_escape_string($pw)."' limit 1"; $result = mysql_query($sql); while ($data = mysql_fetch_object($result)){ if ($data->ctr == 1){ //they're okay to enter the application! $okay = 1; } } if ($okay){ $_SESSION['loginokay'] = true; header("index.php"); }else{ header("login.php"); } ?> |
//****将密码置于站点文件外部
mysql_connect('localhost' , $_SERVER['DB_USER'], $_SERVER['DB_PASSWORD']);