Saturday, February 16, 2013

How to build secure login form with PHP using PDO


Here the full code of secured php login form that use PDO driver.

<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 name="password" type="password" /></td>
</tr>
<tr>
<td><input class="loginBtn" name="login" type="submit" value="Log me in" /></td>
</tr>
</tbody>
</table>
</form>

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 and password = :pass');
$STH->execute(array(':user' => $_POST['user_name'],
':pass' => $_POST['password']));


$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 !!!';
}
Disqus Comments