1 回答

TA貢獻1848條經驗 獲得超2個贊
持久存儲類型的選擇取決于您,但您應該:
切勿將密碼存儲為純文本,password_hash()在存儲之前使用。
然后,在登錄時,用于password_verify()驗證密碼是否與存儲介質(例如數據庫/平面文件)中的哈希匹配。
例子:
<?php
echo password_hash("somepassword", PASSWORD_DEFAULT);
$hash = '$2y$10$f.iC/tadtwSws25fW2zRg./.xlY.mRK82Ys9M4acbPU/b614vA1vy';
if (password_verify('somepassword', $hash)) {
echo 'The password is valid!';
} else {
echo 'The password is not valid';
}
你可以玩這個演示
更新:平面文件 ( .json) 用戶存儲/登錄驗證腳本的簡單示例。您仍然需要對用戶輸入進行數據驗證和清理,并確定平面文件存儲是否是最佳解決方案/是否足以滿足您的應用程序所需的安全級別。
有兩個文件:
index.php應用程序 - 用戶商店/登錄驗證
users.json平面文件數據庫(用戶憑據:name和password)
index.php呈現兩種形式,第一種可用于添加用戶users.json,第二種用于登錄驗證。
index.php
<?php
function getForm(string $submitName, string $submitValue)
{
$form = <<<HEREDOC
<form method="POST">
<label for="username">User Name : </label>
<input type="text" name="username" id="username" required>
<label for="password">Password : </label>
<input type="text" name="password" id="password" required>
<input type="submit" name="$submitName" value="$submitValue">
</form>
HEREDOC;
return $form;
}
// build forms
$userForm = getForm('submit_user', 'Add User');
$loginForm = getForm('submit_login', 'Login');
/* add a new user to flat file database */
echo $userForm;
if (isset($_POST['submit_user'])) {
// retrieve user input - you still need to do data validation and sanitizing
$userName = (isset($_POST['username'])) ? $_POST['username'] : null;
$passWord = (isset($_POST['password'])) ? $_POST['password'] : null;
$passWord = password_hash($passWord, PASSWORD_DEFAULT); // store a hash
// get user.json file
$file = "./users.json";
$users = json_decode(file_get_contents($file), true);
// insert new user credentials
$users['users'][] = ['name' => $userName, 'password' => $passWord];
// write to flat file database
file_put_contents($file, json_encode($users));
}
/* login - verify user credentials */
echo $loginForm;
if (isset($_POST['submit_login'])) {
// retrieve user input - you still need to do data validation and sanitizing
$userName = (isset($_POST['username'])) ? $_POST['username'] : null;
$passWord = (isset($_POST['password'])) ? $_POST['password'] : null;
// get user.json file
$file = "./users.json";
$users = json_decode(file_get_contents($file), true);
// verify user
foreach ($users['users'] as $key => $value) {
if (strtolower($value['name']) === strtolower($userName)) {
$hash = $value['password'];
$verify = password_verify($passWord, $hash); // verify
if ($verify === true) {
echo 'User Login Validated';
} else echo 'Login Not Valid';
}
}
}
平面文件用戶數據庫:users.json
{
"users": [
{
"name": "Jack",
"password": "$2y$10$FBLkEDGX3I6HAVgptJ6q1ujo5K6cFtZn2wNKXKUhoWGNtcwfsRlpi"
},
{
"name": "Jill",
"password": "$2y$10$yKp79.HujKW3yFvxPDYvqePcUJ9uLWJ92d5TpSy62YtuRTezWrsna"
},
{
"name": "Annie",
"password": "$2y$10$eWctVmNAadkf138J0iTVr.5u7vmRl9vcglAhSEjbp0WqQphKFjwYC"
}
]
}
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報