1).不要相信任何來自不受本身直接控制的數據源中的數據。包括但不限於:php
2).解決辦法:過濾輸入。刪除不安全的字符,在數據到達應用的存儲層以前,必須過濾數據。須要過濾的數據包括不限於:HTML、SQL查詢和用戶資料信息。html
htmlentities($input, ENT_QUOTES, 'UTF-8')
過濾輸入。或者使用HTML Purifier。缺點是慢filter_var()
和filter_input()
過濾用戶資料信息3).驗證數據:也可使用filter_var()
,驗證成功返回要驗證的值,失敗返回false
。可是這個函數沒法驗證全部數據,因此可使用一些驗證功能組件。例如aura/filter
或者symfony/validator
4)轉義輸出:任然可使用htmlentities
這個函數,一些模板引擎也自帶了轉義功能。git
1).絕對不能知道用戶的密碼。
2).絕對不要約束用戶的密碼,要限制的話只限制最小長度。
3).絕對不能使用電子郵件發送用戶的密碼。你能夠發送一個修改密碼的連接,上面帶一個token驗證是用戶本人就好了。
4).使用bcrypt
計算用戶密碼的哈希值。加密和哈希不是一回事,加密是雙向算法,加密的數據能夠被解密。可是哈希是單項算法,哈希以後的數據沒法被還原,想同的數據哈希以後獲得的數據始終是相同的。使用數據庫存儲經過bcrypt
哈希密碼以後的值。
5).使用密碼哈希API簡化計算密碼哈希和驗證密碼的操做。下面的註冊用戶的通常操做github
POST /register.php HTTP/1.1
Content-Length: 43
Content-type: application/x-www-form-urlencoded
email=xiao@hello.world&password=nihao複製代碼
下面是接受這個請求的PHP文件web
<?php
try {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email) {
throw new Exception('Invalid email');
}
$password = filter_iput(INPUT_POST, 'password');
if (!$password || mb_strlen($password) < 8) {
throw new Exception('Password must contain 8+ characters');
}
//建立密碼的哈希值
$passwordHash = password_hash(
$password,
PASSWORD_DEFAULT,
['cost' => 12]
);
if ($passwordHash === false) {
throw new Exception('Password hash failed');
}
//建立用戶帳戶,這裏是虛構的代碼
$user = new User();
$user->email = $email;
$user->password_hash = $passwordHash;
$user->save();
header('HTTP/1.1 302 Redirect');
header('Location: /login.php');
} catch (Exception $e) {
header('HTTP1.1 400 Bad Request');
echo $e->getMessage();
}複製代碼
6).根據機器的具體計算能力修改password_hash()的第三個值。計算哈希值通常須要0.1s-0.5s。
7).密碼的哈希值存儲在varchar(255)類型的數據庫列中。
8).登陸用戶的通常流程算法
POST /login.php HTTP1.1
Content-length: 43
Content-Type: application/x-www-form-urlencoded
email=xiao@hello.wordl&pasword=nihao複製代碼
session_start();
try {
$email = filter_input(INPUT_POST, 'email');
$password = filter_iinput(INPUT_POST, 'password');
$user = User::findByEmail($email);
if (password_verify($password, $user->password_hash) === false) {
throw new Exception(''Invalid password);
}
//若是須要的話,從新計算密碼的哈希值
$currentHasAlgorithm = PASSWORD_DEFAULT;
$currentHashOptions = array('cost' => 15);
$passwordNeedsRehash = password_needs_rehash(
$user->password_hash,
$currentHasAlgorithm,
$currentHasOptions
);
if ($passwordNeedsRehash === true) {
$user->password_hash = password_hash(
$password,
$currentHasAlgorithm,
$currentHasOptions
);
$user->save();
}
$_SESSION['user_logged_in'] = 'yes';
$_SESSION['user_email'] = $email;
header('HTTP/1.1 302 Redirect');
header('Location: /user-profile.php');
} catch (Exception) {
header('HTTP/1.1 401 Unauthorized');
echo $e->getMessage();
}複製代碼
9).PHP5.5.0版本以前的密碼哈希API沒法使用,推薦使用ircmaxell/password-compat組件。數據庫
PHP專題系列目錄地址:github.com/xx19941215/…
PHP專題系列預計寫二十篇左右,主要總結咱們平常PHP開發中容易忽略的基礎知識和現代PHP開發中關於規範、部署、優化的一些實戰性建議,同時還有對Javascript語言特色的深刻研究。安全