patternphpMinor
Login system, PDO and me
Viewed 0 times
andsystemloginpdo
Problem
I have run into a bit of a dilemma. Binding user input and building a prepared statement is all well and good, but what if I need the user input as a variable for a compare?
Can I just create a function to clean the input?
This is the line that worries me:
What I have working so far:
Check that the password matches with the database password if username exists
Binding Function
Can I just create a function to clean the input?
This is the line that worries me:
$password = $_POST['password']What I have working so far:
// QUERY
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
// RESULT SET
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
// EXECUTE
public function execute(){
return $this->stmt->execute();
}Check that the password matches with the database password if username exists
query('SELECT username, password, salt, active FROM wcx_admin WHERE username = :username');
$database->bind(':username', $_POST['username']);
$rows = $database->resultset();
if(isset($rows[0])) {
$salt = $rows[0]['salt'];
$dbpass = $rows[0]['password'];
$password = hash("sha512", $password . $salt);
}
if($password !== $dbpass) {
echo 'Incorrect Username or Password';
}
}
?>Binding Function
// BIND
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}Solution
You should also make heavy use of the filter functions of PHP.
query("SELECT `username`, `password`, `active` FROM `admin` WHERE `username` = :username AND `password` = :password LIMIT 1");
$database->bind(":username", $username);
$result = $database->resultset();
if (isset($result[0]) && password_verify($password, $result[0]["password"])) {
echo "Welcome!";
}
}
}Code Snippets
<?php
if (filter_input(INPUT_POST, "form_id", FILTER_UNSAFE_RAW) === filter_input(INPUT_SESSION, "form_id", FILTER_UNSAFE_RAW)) {
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$password = filter_input(INPUT_POST, "password", FILTER_UNSAFE_RAW);
if ($username && $password) {
$database->query("SELECT `username`, `password`, `active` FROM `admin` WHERE `username` = :username AND `password` = :password LIMIT 1");
$database->bind(":username", $username);
$result = $database->resultset();
if (isset($result[0]) && password_verify($password, $result[0]["password"])) {
echo "Welcome!";
}
}
}Context
StackExchange Code Review Q#55549, answer score: 2
Revisions (0)
No revisions yet.