PHP LOGIN Problems
Posted: Fri Feb 06, 2015 8:22 pm
Hi, I have this PHP code that I'm working on. From my 'calcutations' its supposed to work but Its not working as it should. And I need help. Please help me fix it
index.php
authenticate.php
index.php
Code: Select all
<?php
$errors = array(
1=>"Invalid user name or password, Try again",
2=>"Please login to access this area"
);
$error_id = isset($_GET['err']) ? (int)$_GET['err'] : 0;
if ($error_id == 1) {
echo '<p class="text-danger">'.$errors[$error_id].'</p>';
}elseif ($error_id == 2) {
echo '<p class="text-danger">'.$errors[$error_id].'</p>';
}
?>
<form action="authenticate.php" method="POST" class="form-signin col-md-8 col-md-offset-2" role="form">
<input type="text" name="username" class="form-control" placeholder="Username" required autofocus><br/>
<input type="password" name="password" class="form-control" placeholder="Password" required><br/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>authenticate.php
Code: Select all
<?php
require("database-config.php");
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
role
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $dbh->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
if($result->rowCount() == 0){
header('Location: index.php?err=1');
}else{
$row = $result->fetch(PDO::FETCH_ASSOC);
session_regenerate_id();
$_SESSION['sess_user_id'] = $row['id'];
$_SESSION['sess_username'] = $row['username'];
$_SESSION['sess_userrole'] = $row['role'];
echo $_SESSION['sess_userrole'];
session_write_close();
if( $_SESSION['sess_userrole'] == "admin"){
header('Location: adminhome.php');
}else{
header('Location: userhome.php');
}
}
}
}
?>