我需要爲當前項目實現一些安全的PHP登錄。 我用pdo編寫了一些準備好的陳述,並記住了舊代碼。我需要建議來實現更安全的可能,或者檢查是否證明sql注入攻擊。試圖用PHP構建安全登錄
<form action="validate.php" method=post>
<table class="loginForm">
<thead></thead>
<tbody>
<tr>
<td>UserName:</td>
<td><input name=user_name></td>
</tr>
<tr>
<td>Pass:</td>
<td><input type=password name=password></td>
</tr>
<tr>
<td><input class=loginBtn type=submit value='Log me in' name=login></td>
</tr>
</tbody>
</table>
</form>
Validate.php
session_start();
try {
$host = 'localhost';
$dbName = 'xxx';
$dbUser = 'xxx';
$dbPass = 'xxx';
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbName", $dbUser, $dbPass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
$STH = $DBH->prepare("SELECT * FROM `Admins` WHERE `username` = '$user_name' AND password='$password'");
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
$affected_rows = $STH->fetchColumn();
if($affected_rows == 1) {
//add the user to our session variables
$_SESSION['username'] = $user_name;
header("Location: http://www.mysite.com/administration/index.php");
exit;
//print 'allowed';
}
else {
print 'access is not allowed !!!';
}
更新時間: 感謝接受的答案波紋管我的查詢現在的編碼方式類似於這樣
$STH = $DBH->prepare('SELECT * FROM Admins
WHERE username = :user and password = :pass');
$STH->execute(array(':user' => $_POST['user_name'],
':pass' => $_POST['password']));
這很好。 現在我只想確定我的身份驗證是否足以在管理頁面上使用它,例如: session_start();
try {
$host = 'xx';
$dbName = 'xxxx';
$dbUser = 'xxxxx_first';
$dbPass = 'xxx';
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbName", $dbUser, $dbPass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
if (empty($_SESSION['username'])) {
die('To access pages you have to be loged in.
<a href="/administration/login.php">log in</a> ');
}
你使用https發送表單到服務器? – Gordon 2012-04-01 11:13:02
也許這有助於 http://stackoverflow.com/questions/549/the-definitive-guide-to-forms-based-website-authentication – bescht 2012-04-01 11:16:26
我認爲你是以純文本存儲密碼 - 你應該哈希它們,用SHA1說。 – halfer 2012-04-01 11:40:12