PHP failing to login - could it the sha256 hashing? - php

Trying to develop a simple CRUD application piecing together tutorials from the net, just now I'm working on the login and this is proving to be a slight problem. I can register a user and it will add a record to the database, but when I try logging in it fails every time. My code sample is below, any help would be greatly appreciated.
Index.php
require("config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "
SELECT
userid,
username,
password,
salt,
email
FROM wt_users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->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']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password == $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['users'] = $row;
header("Location: secret.php");
die("Redirecting to: secret.php");
}
else{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
config.php
// These variables define the connection information for your MySQL database
$username = "*******";
$password = "***********";
$host = "*********";
$dbname = "********";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
loggedin.php
require("config.php");
if(empty($_SESSION['users']))
{
header("Location: index.php");
die("Redirecting to index.php");
}
Plan is to display a CRUD interface once the user has logged in, but for the moment I can't get them logged in..

Related

MYSQL PDO update datetime does nothing [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
Tried for an hour already. Help pls. Basically i want to update lastlogin column(MYSQL datetime) every time a user login. There is no error message and no update is happening. What is going on?
db.php
<?php
// These variables define the connection information for your MySQL database
$username = "root";
$password = "root";
$host = "localhost";
$dbname = "rofl";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
main.php
<?php
include("DB/db.php");
if(!empty($_POST)){
$query = "
SELECT
userID,
password,
salt,
email
FROM user
WHERE
userID = :username
";
$query_params = array(
':username' => $_POST['useridforlogin']
);
try{
$stmt = $db->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['passwordforlogin'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
date_default_timezone_set('Asia/xxxxxx');
$timestamp = date('Y/m/d h:i:s a', time());
$query2 = "UPDATE user SET lastlogin= ':lastlogin' where userID = ':username'";
$query_params2 = array(
':lastlogin' => $timestamp,
':username' => $_POST['useridforlogin']
);
try {
$stmt2 = $db->prepare($query2);
$result2 = $stmt2->execute($query_params2);
} catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
I think the problem comes from your date format.
Try replacing 'Y/m/d h:i:s a' by 'Y/m/d h:i:s' (removed the a)

Password verify using PDO returns nothing

I'm trying to create a login page but when I try and log in I get a blank page returned, I get no errors either. I want to return a success or failure message based on the outcome of the login script. Where am I going wrong?
Login page:
try {
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = : username LIMIT 1";
$query = $dbh->prepare( $sql );
$query->execute( array( ':username'=>$username ) );
$results = $query->fetchAll( PDO::FETCH_ASSOC );
foreach( $results as $row ){
if(password_verify($_POST['password'], $password)){
echo 'verified';
}
else
{
echo 'not verified';
}
}
The page to create a user:
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
//sets type to '1' which is used for a user.
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?, type= '1'");
$stmt->execute([$username, $email, $hash]);
echo "<p>Thank you for registering!</p>";
There is a space between the colon and "username"
'username = : username'
^
There should not be any spaces and to read as :username
A few lines below you are using:
array( ':username'=>$username )

PDO Login System not working

I know I'll get a bunch of down-votes, but I am new to PDO and need to make a login system for a little web application. I can't seem to get it right:
<?php
include 'Config.php';
$username = strtolower($_POST['username']);
$password = md5($_POST['password']);
$hidden = $_POST['hidden'];
$submit = $_POST['submit'];
$host = $config['mysql']['host'];
$mysql_user = $config['mysql']['user'];
$mysql_pass = $config['mysql']['pass'];
$db = $config['mysql']['db'];
if(isset($username) && isset($password) && isset($submit) && !isset($hidden)) {
try {
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
$objQuery = $objDatabase->prepare("SELECT * FROM users WHERE username=:username");
$objQuery->bindValue(':username', $username);
$objQuery->execute();
$row = $objQuery->fetch(PDO::FETCH_ASSOC);
if(!empty($row)) {
if($username == $row['username'] && $password == $row['password']) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $row['username'];
header('Location: i/');
} else
header('Location: index.php?err=true&type=1');
} else
header('Location: index.php?err=true&type=2');
} catch(PDOException $e) {
die($e->getMessage());
}
}
?>
I always get error 2 - account not found. I'm logging in with user "test" and password "test". In the database is an account with username "test" and the password is an MD5 hash of "test".
Your sql statement is wrong:
SELECT * FROM users WHERE username=':username'
You should not put your placeholder in quotes as now it is taken literally by mysql.
It should be:
SELECT * FROM users WHERE username=:username
You should also tell PDO to throw exceptions:
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
So that it will tell you when something goes wrong.
Edit: As noted by #LozCheroneツ you also need to execute the query before you can fetch a row:
$objQuery->bindValue(':username', $username);
$objQuery->execute();

PHP validation using PDO not working

I am new to PDO. I have included validation in the following code but it doesnt seem to work and no message appears if users enter the wrong username/password. Please show me where I am going wrong. I have numerous times to get this working but no luck. Thanks
<?php
require("config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->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']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: secret.php");
die("Redirecting to: secret.php");
}
else{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
Config.php
<?php
// These variables define the connection information for your MySQL database
$username = "xxxx";
$password = "xxxx";
$host = "xxxxxxx";
$dbname = "xxxxxx";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>

Login users/start session with PDO

Im trying to create a login section on my website using PDO.
So far I've the following...
config.php
// Connect to DB
$username = 'user#site.co.uk';
$password = 'pass';
try {
$conn = new PDO('mysql:host=localhost;dbname=db', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
header.php
// DB Config
include '/assets/config.php';
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
$sth->execute();
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
?>
My browser doesn't display the page however, and when I view my source theres no data contained within, can anybody see where im going wrong?
try this:
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->execute(array(":username" => $login,":password" => $pass));
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
echo $sth->rowCount();
}
make sure you have username "liam" and pass "password" in the database
You have set PDO::ERRMODE_EXCEPTION. This means, you should wrap your statements in a try/catch block and test execute()s return code:
try {
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
if (!$sth->execute()) {
$info = $sth->errorInfo();
echo 'Error: ' . $sth->errorCode() . ' (' . $info[2] . ")\n";
} elseif ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
} catch (PDOException $e) {
echo 'Exception: ' . $e->getMessage() . "\n";
}
and put some trace statements in, of course.

Categories