Undefined property: PDOStatement::$rows - php

I'm not sure why this bit of code:
if($sth->rows == 0){
echo "Incorrect username or password - 1";
}
is pulling the error Undefined property: PDOStatement::$rows. This works just fine on a different PHP script that I basically had changed only a few things. I do however also receive the echo "Incorrect username or password -1" meaning that if statement did run.
Here is the full PHP code.
<?php
$lusername = $_POST['username'];
$lpassword = $_POST['password'];
//Hashing password
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", $cost) . $salt;
$hash = crypt($lpassword, $salt);
// Create connection
$dsn = 'mysql:dbname=weblupne_template3;host=localhost';
$username = 'somethingFreakingCrazyMagical';
$password = 'somethingEvenMoreCrazyFreakingMagical';
try {
$db = new PDO($dsn, $username, $password); // also allows an extra parameter of configuration
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception
} catch(PDOException $e) {
die('Could not connect to the database:<br/>' . $e);
}
//Where to select from
$sth = $db->prepare('SELECT password FROM login WHERE username = :username LIMIT 1');
$sth->bindParam(':username', $lusername);
$sth->execute();
$user = $sth->fetch(PDO::FETCH_OBJ);
if($sth->rows == 0){
echo "Incorrect username or password - 1";
}
else{
//Tests if correct
echo $user->hash;
if ( hash_equals($user->password, crypt($lpassword, $user->password)) ) {
echo "You check out";
}
else{
echo "Incorrect username or password - 2";
}
}
?>

You have to use $sth->rowCount(), there is no property named rows.

Related

checking validation login showing error using pdo

Here is validation form using PDO , Database code which is showing connection to my database is running correctly.
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$con = new PDO("mysql:host=$servername;dbname=filesystem", $username, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
and now i am making connection to open a page after validating from database based on correct username and password , Here is code
if(isset($_POST['submit']))
{
$user=!empty($_POST['user']) ? trim($_POST['user']) :null ;
$password=!empty($_POST['password']) ? trim($_POST['password']) :null;
$sql="select * from users where user='$user' and password='$password'";
if($stmt=$con->query( $sql))
{
if($stmt->fetchColumn()>0)
{
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$u_name=$row['user'];
$u_password=$row['password'];
if($user==$u_name && $password==$u_password)
{
if(isset($_POST['remember']))
{
setcookie('user',$user,time()+60*60*7);
setcookie('password',$password,time()+60*60*7);
}
session_start();
$_SESSION['user']=$user;
echo "<script> window.location.assign('../index.php'); </script>";
exit();
} else {
echo "nothing";
}
} else {
echo"<script>alert('incorrect user name or password')</script>";
echo "<script> window.location.assign('login.php'); </script>";
}
}
}
Now when input credential are right then why this still is keep going in else{echo "nothing";}.Help me please.
As I said above best you change your password column from AES_ENCRYPT to varchar(255) then delete the user on your database and start fresh register the user with php password_hash() then on login verify the stored hash with password_verify()
This is what you will do on register page
<?php
$user = isset($_POST['user']) ? $_POST['user'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
//hash the password
$hash = password_hash($password, PASSWORD_DEFAULT);
$insert = $con->prepare("INSERT INTO users (user,password) VALUES(?,?)")->execute(array($user,$password));
if ($insert) {
echo "User registered success";
} else {
//user not registered handle errors
}
?>
Then on login
<?php
$user = !empty($_POST['user']) ? trim($_POST['user']) : null;
$password = !empty($_POST['password']) ? $_POST['password'] : null;
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$stmt = $con->prepare($sql);
$stmt->bindParam(1, $user, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch();
if ($row && password_verify($password, $row['password'])) { //verify pass
if (isset($_POST['remember'])) {
setcookie('user', $user, time() + 60 * 60 * 7);
setcookie('password', $password, time() + 60 * 60 * 7);
}
$_SESSION['user'] = $user;
header("location:../index.php");
exit();
} else {
echo "incorrect user name or password";
header("location:login.php");
exit();
}
?>
**
NB: When verifying a password store with passwod_hash() do not use any
cleansing mechanism
**

PHP Change Account Password Brakes at verify current password

I am trying to make a Change You Account Password Function for my website.
The login codes are working properly, hashed passwords with bcrypt , log in verifies and confirms that the account name and password are correct with the ones that are entered.
I am trying to use the same algorithm to check the Current pass and Database pass verification ,but something seems to be missing.
I constantly get a different hash from the password that is entered and respectively wrong current password error.
Here is the exact code I use in the php file.
<?php
session_start();
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$client_new_password_err = $client_current_password_err = $client_confirm_new_password_err = $general_err = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$user_check = $_SESSION['login_user'];
$stmt = $conn->prepare("SELECT UserName FROM user_main WHERE UserName='$user_check'");
$stmt->execute();
foreach ($stmt->fetch(PDO::FETCH_ASSOC) as $arr) {
$login_session = $login_session . $arr;
}
if (empty($login_session)) {
$conn = null;
header('Location: login.php');
}
$stmt = $conn->prepare("SELECT Email FROM user_main WHERE UserName='$user_check'");
$stmt->execute();
foreach ($stmt->fetch(PDO::FETCH_ASSOC) as $arr) {
$login_email = $login_email . $arr;
}
}
catch(PDOException $e)
{
echo $stmt . "<br>" . $e->getMessage();
}
$conn = null;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["current-password"])) {
$client_current_password = test_input($_POST['current-password']);
$cost = [
'cost' => 11,
];
$client_current_hashed_password = password_hash($client_current_password, PASSWORD_BCRYPT, $cost);
} else {
$client_current_password_err = "No input on Current Password";
}
if (!empty($_POST['new-password'])) {
$client_new_password = test_input($_POST['new-password']);
$cost = [
'cost' => 11,
];
$client_new_hashed_password = password_hash($client_new_password, PASSWORD_BCRYPT, $cost);
} else {
$client_new_password_err = "No input on New Password";
}
if (!empty($_POST['confirm-new-password'])) {
$client_confirm_new_password = test_input($POST['confirm-new-password']);
$cost = [
'cost' => 11,
];
$client_confirm_new_hashed_password = password_hash($client_confirm_new_password, PASSWORD_BCRYPT, $cost);
} else {
$client_confirm_new_password_err = "No input on New Password";
}
if ($client_new_hashed_password == $client_confirm_new_hashed_password) {
$to_change_pass = 1; // not yet implemented
} else {
$to_change_pass = 0; // not yet implemented
}
}
if (!empty($client_current_hashed_password) && !empty($client_new_hashed_password) && !empty($client_confirm_new_hashed_password)) {
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$user_check = $_SESSION['login_user'];
$stmt = $conn->prepare("SELECT Password FROM user_main WHERE UserName='$user_check'");
$stmt->execute();
foreach ($stmt->fetch(PDO::FETCH_ASSOC) as $db_hash_pass) {
if(password_verify($client_current_password, $db_hash_pass)) {
$stmt = $conn->prepare("UPDATE user_main SET Password = '$client_new_hashed_password' WHERE UserName = '$user_check'");
} else {
$general_err = "Entered current password does not match the actual password for this account. Please try again.";
}
}
}
catch(PDOException $e)
{
echo $stmt . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
The main question is how should I be checking if the inputted current pass matches the one on the database?
Should i be using the hashed version of the pass entered by the client or should i be using the plain text password?
This is the login password verify code which is 100% operational
if (!empty($_POST['password'])) {
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$_POST['password'])) {
$usernameErr = 'Only Letters and Numbers';
} else {
$client_password = test_input($_POST['password']);
if(password_verify($client_password, $hashed_password)) {
$_SESSION['login_user'] = $client_username;
header("location: profile.php");
where $hashed_password is drawn from the database column Password with username match and here it works.
As you can see I have limited passwords to letters and numbers only so -
Bonus question : By allowing all characters to be used in a password , does that impose any type of injection threat?
Don't hash, but verify instead. – jeroen 13 mins ago
Removed hashing from the code entirely and it is ok now, it works by using password_verify($client_current_password, $db_hash_pass).
Thank you jeroen for the push u gave me to do this :D

PHP PDO Error when fetching hashed strings from SQL table

As I was changing my MySQLi to PDO, I encountered an error when fetching hashed strings from my users table.
This was the code I used before:
CheckPassword VERIFIES VALID USING MYSQLI
$mysqli = new mysqli("localhost","_USER_","_PASS_","_DB_");
$username = '_USERNAME_';
$pass = '_PASSWORD_';
$sql = "SELECT * FROM `users` WHERE username='$username' LIMIT 1";
$result = $mysqli->query($sql);
if($assoc = $result->fetch_assoc()){
$db_pass = $assoc['userpass'];
require 'PasswordHash.php';
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if($hasher->CheckPassword($pass, $db_pass)) {
echo "valid"; // VERIFIES VALID
} else {
echo "invalid";
}
}
The reason why I switched to PDO was to prevent SQL Injections.
But now: CheckPassword VERIFIES INVALID USING PDO
$pdo = new PDO('mysql:dbname=_DB_;host=localhost', '_USER_', '_PASS_',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$username = '_USERNAME_';
$pass = '_PASSWORD_';
$stmt = $pdo->prepare('SELECT * FROM `users` WHERE username = :u LIMIT 1');
$stmt->bindParam(':u', $username);
$stmt->execute();
if($fetch = $stmt->fetch(PDO::FETCH_ASSOC)){
$db_pass = $fetch['userpass'];
require 'PasswordHash.php';
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if($hasher->CheckPassword($pass, $db_pass)) {
echo "valid";
} else {
echo "invalid"; // VERIFIES INVALID
}
}
}
How is it that; MySQLi fetches the hashed string different compared to PDO? No matter what encryption I use for hashing the passwords, it CANNOT validate them as true when fetching using PDO, BUT only when fetching using MySQLi?
The reason because when you comparing the password that the user enter and the password that in the database , its different , the pass that the user enter to log in to his account is not hashed while the one in the database is , so we need a way to hash the entered pass and validate it with the already hashed pass in the database . How to do that ? here
This is an example from a code that i use in my Control panel :
<?php
// connect to your database
if(isset($_POST['btn-login']))
{
$User_name = $_POST['userlogin'];
$password_user = $_POST['pass'];
$FetchUserData = $conn->prepare("SELECT * FROM users WHERE userlogin = ?");
$FetchUserData->execute(array($User_name));
$FetchedData = $FetchUserData->fetch(PDO::FETCH_ASSOC);
if ($FetchedData)
{
$password = $FetchedData['userpassword']; // Save the fetched password inside variable
$isPasswordCorrect = password_verify($password_user, $password);
if( $password_user == $isPasswordCorrect )
{
$_SESSION['login_user']=$User_name;
header("location: home.php");
}
else
{
echo "Password is wrong":
}
}
else
{
echo "User is not exist ";
}
}
?>
This Code line is the code used to hash the enterd pass with the exist pass in the database :
$isPasswordCorrect = password_verify($password_user, $password);
Small explanation :
password_verify(parameterA,parameterB)
parameterA : The password that you want it to be validate .
parameterB : the password that you want it to be validated with .(
database that is stored in the database )
Hope this answer be helpful for you .

Password_verify in PHP

So I'm enabling users to create accounts with a username and password. I have managed to encrypt the password when a user creates a new account using:
$hash = password_hash($password, PASSWORD_BCRYPT);
However I'm having trouble with password_verify when logging in, could someone please help me with what I have? I know it's something like this:
password_verify($password, $hash)
But I don't know how to structure it or where to add it in the code. Thanks in advance. This is what I have:
<?php
if (isset($_GET["username"]) && isset($_GET["password"]) ){
$username = $_GET["username"];
$password = $_GET["password"];
$result = login( $username, $password);
echo $result;
}
function makeSqlConnection()
{
$DB_HostName = "";
$DB_Name = "";
$DB_User = "";
$DB_Pass = "";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
function login($username, $password)
{
$con = makeSqlConnection();
$sql = "select * from login where username = '$username' and password = '$password';";
$res = mysql_query($sql,$con) or die(mysql_error());
$res1 = mysql_num_rows($res);
disconnectSqlConnection($con);
if ($res1 != 0) {
return 1;
}else{
return 0;
}// end else
}// end of Function
?>
The general practice is as follows:
Fetch password hash from the database where the username = the inputted username.
If rows are found, then there's a user
Now you compare the inputted password against the hash stored in the database.
I'll outline the above flow in some pseudo code for you here:
$query = SELECT password FROM users WHERE username = '$username'
$data = FETCH_THE_DATA($query);
if(password_verify($USER_INPUTTED_PASSWORD, $data['password'])) {
// password is correct
} else {
// password is in-correct
}
Notes
Stop using mysql_* functions. The library is deprecated as it's unreliable and will be removed in future releases of PHP.
You're better off using PDO or MySQLi Prepared Statements
You should always read the manual - password_verify(), it states clearly that you compare the "user inputted password" against the hashed version which is stored in your database.
Since I'm feeling good and sleepy today, I'll write a bunch of codes.
This is an example how to use PDO with prepared statement. You will have to tweak it according to your needs and you have to check if the post/get not empty as well.
I prefer to use POST request for login so this example will use POST request..
This is my user class. Which use placeholders and binding instead of passing the parameters into the query directly. This will give some protections against SQL injection attack.
class User{
private $dbh;
function __construct(){
$this->dbh = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME.';charset=utf8mb4', DB_USER, DB_PASSWORD) or die('db connect error');
}
function create($username, $password){
$status = false;
try{
$stmt = "INSERT INTO login (username, password)
VALUES (?, ?)";
$qry = $this->dbh->prepare($stmt);
$qry->bindParam(1, $username);
$qry->bindParam(2, $password);
$status = $qry->execute();
}catch(PDOException $e){
$e->getMessage();
}
$qry->closeCursor();
return $status;
}
public function getPassword($username){
$status = false;
try{
$stmt = "SELECT * FROM login WHERE username = ? LIMIT 1";
$qry = $this->dbh->prepare($stmt);
$qry->bindParam(1, $username);
$qry->execute();
$status = $qry->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $e){
$e->getMessage();
}
$qry->closeCursor();
return $status;
}
}
This is how to create the user. Note that I don't check if the username already exist. You can either implement it yourself or use unique index on username column provided that the collation is case insensitive.
I have also increased the cost from the default that is 10 and I defined PASSWORD_DEFAULT to be used because I want the PHP engine to always use the strongest available algorithm (currently bcrypt).
function hashPassword($password){
$password = password_hash($password, PASSWORD_DEFAULT,array('cost' => 16));
return $password;
}
$user = new User;
$_POST['password'] = hashPassword($_POST['password']);
if(!$user->create(trim($_POST['username']),$_POST['password'])){
echo 'Failed creating user';
}else{
echo 'User created';
}
This is how to verify the password.
$user = new User;
$getPassword = $user->getPassword(trim($_POST['username']));
if(!$getPassword){
echo 'Error fetching user';
}else{
if(!password_verify($_POST['password'], $getPassword['password'])){
echo 'Login failed';
}else{
echo 'Login successful';
}
}

Match passwords after using CRYPT_BLOWFISH

I have successfully created my passwords and am inserting them into the database using CRYPT_BLOWFISH. However I do no know how to match the crypted passwords in the database to the passwords the user is entering to login. Any help is greatly appreciated thanks.
To generate the password from the users input I use:
REGISTER.PHP
//If there are no errors or returned_records and the form is submitted let's submit the info and register the user
else if(!$error_msg && !$returned_record && $_POST['register']){
//Place the newly hased/encrypted password into our new_password variable
function generateHash($password_1){
if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){
$salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22);
return crypt($password_1, $salt);
}//End If
}//End Function genrateHash*/
$new_password = generateHash($password_1);
$pass = $new_password;
//Build our query
$sql = ("INSERT INTO members (username, email, password_1) VALUES (?,?,?)");
//Prepare our query
$stmt = $mysqli->prepare($sql) or die("Failed Execution");
//Bind the fields and there paramters to our query
$stmt->bind_param('sss', $username, $email, $new_password);
//Execute the query
$stmt->execute();
echo $stmt->error;
header('Location: http://www.yourschoolsincanada.com/english/register/registration-success/');
exit();
}
LOGIN.PHP
if(isset($_POST['login'])){
$username = $_POST['username'];
$password_1 = $_POST['password_1'];
$sql = "SELECT member_id, username, password_1 FROM members WHERE username = ? AND password_1 = ? LIMIT 1";
//Prepare our query
if($stmt = $mysqli->prepare($sql)){
//Bind the Parameters to the query
$stmt->bind_param('ss', $username, $password_1);
//Execute the query
$result = $stmt->execute();
/*Store our result to get properties*/
$stmt->store_result();
//Get the number of rows
$num_of_rows = $stmt->num_rows;
//Bind the results of what the query gave us to our three variables
$stmt->bind_result($id, $username, $password_1);
if(crypt($password_1, $pass) == $pass){
echo "Match";
}
else{
echo "Passwords don't match";
}
}
Working Demo
I've gotten the following to work. The HTML form and PHP all run inside the same page.
<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');
$mysqli = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
if(isset($_POST['login'])){
$username = htmlentities(trim($_POST['username']));
$username = mysqli_real_escape_string($mysqli, $username);
$password = trim($_POST['password']);
$query = mysqli_query($mysqli, "SELECT username, password_1 FROM members WHERE username = '$username'");
$row = mysqli_fetch_assoc($query);
$numrows = mysqli_num_rows($query);
$dbuser = $row['username'];
$dbpass = $row['password_1'];
$hashed_password = crypt($password, $dbpass);
// var_dump($dbuser); // For testing purposes only, can be removed
echo "<hr>";
// var_dump($dbpass); // For testing purposes only, can be removed
if( ($username == '') || ($password == '') ) {
$error_string = '<font color=red>You have left either the username or password field blank!</font>';
echo $error_string;
}
if ($numrows == 0)
{
$error_string = '<font color=red>No username can be found!</font>';
echo $error_string;
}
else if ($numrows == 1)
{
if ($hashed_password == $dbpass)
{
$error_string = '<font color=red>Details checked out</font>';
echo $error_string;
}
}
else {
$error_string = '<font color=red>There was an error. Please contact an Admin</font>';
echo "SORRY Charlie!";
}
} // brace for isset login
?>
<form action="" method="post">
Username:
<input type="text" name="username">
<br>
Password:
<input type="text" name="password">
<br>
<input type="submit" name="login" value="Submit">
</form>
Original answer
The following should work, since I've gotten a "match" using the following inside the same file.
Read the comments inside the code.
<?php
$password_1 = "1234567890"; // User-entered password
function generateHash($password_1){
if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){
$salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22);
return crypt($password_1, $salt);
}
}
// Remove the echo. For testing purposes only
echo $new_password = generateHash($password_1);
$pass = $new_password;
echo "<br>";
echo $pass;
echo "<hr>";
// Verify that the password matches and use in your login page
// Syntax: if(crypt($password_entered, $password_hash) == $password_hash)
if(crypt($password_1,$pass) == $pass) {
// password is correct
echo "Match.";
}
else {
echo "No match.";
}
EDIT
Password generator:
<?php
$password_1 = "1234567890"; // User-entered generated password
// or from a form
// $password_1 = $_POST['password']; // User-entered generated password
function generateHash($password_1){
if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){
$salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22);
return crypt($password_1, $salt);
}
}
// here you can enter the password into DB
// since we have a successful echo
// Remove the echo. For testing purposes only
echo $new_password = generateHash($password_1);
$pass = $new_password;
echo "<br>";
echo $pass;
echo "<hr>";
Login check:
$password_1 = $_POST['password']; // User-entered password
// DB codes example:
$query = mysqli_query($con, "SELECT password FROM users WHERE password='".$password_1."'");
// Verify that the password matches and use in your login page
// Syntax: if(crypt($password_entered, $password_hash) == $password_hash)
if(crypt($password_1,$pass) == $pass) {
// password is correct
echo "Match.";
}
else {
echo "No match.";
}

Categories