我需要为当前项目实现一些安全的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