Password verify using PDO returns nothing - php

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 )

Related

multiple query in one php file , i tried to write the code but i am not getting it done

I want to execute mysql_qry1 also , how should i do it , till now my code is working fine but i want to execute the second query also(mysql_qry1) , please help.
<?php
require "conn.php";
$status=1;
$user_name = $_POST["user"];
$user_pass = $_POST["pass"];
$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
$mysql_qry1 = "insert into login_status (username, status) values ('$user_name','$status)";
$result = mysqli_query($conn , $mysql_qry);
if(mysqli_num_rows($result)==1) {
echo "login success , Hello";
}
else {
echo "login failed";
}
$conn->close();
?>
Your SQL is one of most dangerous, please try to re-write:
//$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
I m not sure what is in our conn.php, here is one of the example to update (PDO):
$sql = 'select 1 from tbl_client where username = :user and password = :pass';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':pass' => $user_pass);
$row = $sth->fetch(PDO::FETCH_NUM);
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
$sql = 'insert into login_status (username, status) values (:user, :status)';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':status' => $status);
OK, so your conn.php is using mysqli_ . Please refer to this page for help:
http://php.net/manual/en/mysqli-stmt.bind-param.php
And change above answer to:
$sql = 'select 1 from tbl_client where username = ? and password = ?';
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $user_name, $user_pass);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch();
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
I have not used mysqli before, so not quite familiar, even php.net is hard to find out some docs about it. Please google howto use: mysqli_stmt_fetch() and replace it with proper code
Why not update your conn.php to use PDO? (be careful, you might need to update all your other pages as well which are calling this file):
// conn.php
$pdo = 'mysql:host=' . $server_name . ';dbname=' . $db_name;
$dbL = new PDO($pdo, $mysql_username, $mysql_password);

PHP failing to login - could it the sha256 hashing?

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..

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.

Login script using PDO extension not working

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Categories