I'm trying to create a login system using Slim Jquery and Ajax. I've got the log in part working with minimal issues, now I just need to be able to hash the password. I know I can use md5, sha1 and/or salt to hash but I know that it is recommenced that password_hash is used instead. I know how to hash with any of the other 3 I mentioned because while using bindParam you can just place it around the variable. My question is, how do I use password_hash with bindParam. The closest answer I found on this site didn't do much to help.
My current code is:
$app->post('/addUser/', 'addUser');
function addUser()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "INSERT INTO users(firstName, lastName, userName, password) VALUES (:firstName, :lastName, :userName, :password)";
try{
$dbConnection();
$stmt=$db->prepare($sql);
$stmt->bindParam("firstName", $q->firstName);
$stmt->bindParam("lastName", $q->lastName);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
$db=null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
Verify Code:
$app->post('/logIn/', 'lonIn');
function logIn()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "SELECT * FROM users WHERE userName=:userName";
try{
$db = getConnection();
$stmt=$db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$execute = $stmt->execute();
$db = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if($execute == true)
{
$array = $stmt->fetch(PDO::FETCH_ASSOC);
$hashedPassword = $array['password'];
if(password_verify($q->password), $hashedPassword))
{
echo 'Valid';
}
else
{
echo 'Invalid';
}
}
}
Any help would be appreciated.
To encrypt password you need to create a new variable $hashedPassword which you will store in the db for each user. When verifying the user you will select a user from the db passing their username and using password_verify($passToBeVerified,$ourHashedpasswordfromDb) this will return a boolean.
$app->post('/addUser/', 'addUser');
function addUser() {
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "INSERT INTO users(firstName, lastName, userName, password) VALUES (:firstName, :lastName, :userName, :password)";
try {
$dbConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":firstName", $q->firstName);
$stmt->bindParam(":lastName", $q->lastName);
$stmt->bindParam(":userName", $q->userName);
$stmt->bindParam(":password", $hashedPassword);
$execute = $stmt->execute();
if ($execute == true) {
$verifyUser = verifyUser($q->password, $q->userName);
if ($verifyUser == TRUE) {
echo 'valid Username and Password';
} else {
echo 'Invalid Username and password';
}
}
$db = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
function verifyUser($passWordToVerify, $userNameToVerify) {
// $request = \Slim\Slim::getInstance()->request();
// $q = json_decode($request->getBody());
//Select a user data according to their username
$sql = "select firstName, lastName, userName, password from users where userName = :userName";
try {
$dbConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":userName", $userNameToVerify);
$execute = $stmt->execute();
$db = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
if ($execute == True) {
/*
* if the query executes and returs the user saved user details lets now compare
* the password from the db and the password that the user has entered
*/
$array = $stmt->fetch(PDO::FETCH_ASSOC);
$hashedPassword = $array['password'];
if (password_verify($passWordToVerify, $hashedPassword)) {
echo 'Password is valid!';
return true;
} else {
echo 'Invalid password.';
return false;
}
}
}
Related
The password is hashed and enters the db when i try to verify it it returns false every time i have echoed out the password going in and the db password the column in the database is the correct size
<?php
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function register($uname, $umail, $upass)
{
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->conn->prepare("INSERT INTO USERS(USERNAME, EMAIL, PASSWORD) VALUES(:uname, :umail, :upass)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function doLogin($uname, $umail, $upass)
{
try
{
$stmt = "SELECT USERID, USERNAME, EMAIL, PASSWORD, FIRSTNAME FROM USERS WHERE USERNAME = :uname OR EMAIL = :umail ";
$stmt = $this->conn->prepare($stmt, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->bindparam(':uname', $uname);
$stmt->bindparam(':umail', $umail);
$stmt->execute();
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
$db_password = $userRow['PASSWORD'];
$sql = "SELECT COUNT(*) FROM USERS WHERE USERNAME = :uname OR EMAIL = :umail";
$sql = $this->conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindparam(':uname', $uname);
$sql->bindparam(':umail', $umail);
$sql->Execute();
$row = $sql->fetch(PDO::FETCH_ASSOC);
if($row == 1)
{
if(password_verify($upass, $userRow['PASSWORD']))
{
$_SESSION['USER_SESSION'] = $userRow['USERID'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['USER_SESSION']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function doLogout()
{
session_destroy();
unset($_SESSION['USER_SESSION']);
return true;
}
}
?>
edit to the code i have added the whole user class but it is still returning false the password in the db looks like this $2y$10$16aMCo14n.QyON8dFsaFL..6Fi92LuBdWMCI3eAv3WHKJTblJKQ6q the column in the db is set to nvarchar (255) not null
This is the register.php it links to the User.class.php **
**I am working with the PDO statement for the database connection
**When I click on the submit button the form is send to my database but it doesn't open the index.php **
include_once("classes/User.class.php");
try {
if( !empty ($_POST)){
if($_POST['password'] == $_POST['password_confirmation']) {
$user = new User();
$user->setEmail($_POST['email']);
$user->setUsername($_POST['username']);
$user->setFullname($_POST['fullname']);
$user->setPassword($_POST['password']);
if($user->register()){
$user->login();
}
}
}
}
catch (Exception $e) {
$feedback = $e->getMessage();
}
?>
**This is the User.class.php **
class User {
private $email;
private $username;
private $fullname;
private $password;
public function register(){
//connection
$conn = new PDO('mysql:host='localhost'; dbname='databasename'', 'root', 'root');
//query (insert)
$statement = $conn->prepare("insert into users (email, username, fullname, password)
values(:email, :username, :fullname, :password)");
// bcrypt
$options = [ 'cost'=> 12 ];
$password = password_hash($this->password, PASSWORD_DEFAULT, $options);
$statement->bindParam(':fullname', $fullname);
$statement->bindParam(':email', $email);
$statement->bindParam(':username', $username);
$statement->bindParam(':password', $password);
//execute
$result = $statement->execute();
//return true/false
return $result;
}
public function login() {
if(!isset($_SESSION['loggedin'])) {
header('Location:login.php');
echo $feedback = "thanks for creating an account.";
}
}
}
Your line 3 on User.class.php have an error it should be like this:
$conn = new PDO('mysql:host=HOSTNAME;port=3306;dbname=DATABASENAME;charset=UTF8;', USERNAME, PASSWORD);
change HOSTNAME, DATABASENAME, USERNAME and PASSWORD to the correct.
I'm creating a back end to my website and running into issues with the login user part.
The user registration into the database is made with the password_hash function using the code below:
UserReg.php :
<?php
require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);
if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}
$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);
add_user($mysqli,$username, $token);
function add_user($mysqli,$username, $token) {
$query = $mysqli->prepare("INSERT INTO users(username, password) VALUES
(?,?)");
$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();
if(!$result) {
die($mysqli->error);
}
$query->close();
}
My login form skips to a blank page even when i insert my username and password. Doesn't even go to the login error message.
Login.php
<?php
include 'db.php';
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->bind_result($pass);
while ($result = $stmt->num_rows()) {
if($stmt->password_verify($pwd, $result)) {
echo "Your username or password is incorrect";
} else {
header("Location: Menu.php");
}
}
What am i missing?
Appreciate your help.
I think you need to take a look at password_verify how it works.
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT username, password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if ($stmt->num_rows == 1) { //To check if the row exists
if ($stmt->fetch()) { //fetching the contents of the row
if (password_verify($pwd, $password)) {
$_SESSION['username'] = $username;
echo 'Success!';
exit();
} else {
echo "INVALID PASSWORD!";
}
}
} else {
echo "INVALID USERNAME";
}
$stmt->close();
I have tried out a code for user registration..problem is it gives me {"error":true,"error_msg":"User already existed with abc#abc.com"} even though the user doesn't exists in database..plzz help me out of this..pardon me if am wrong some were..!
here gose my /DB_Function.php/code
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
/**
* Storing new user
* returns user details
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
echo 'Error accessing database: ' . $e->getMessage();
}
return false;
}
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = $email LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n>0){
return true;
}else{
return;
}
}
catch (Exception $e) {
echo 'Error accessing database: ' . $e->getMessage();
}
}
}
?>
And here gose my /*register.php code */
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['mobile'])) {
// receiving the post params
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$mobile = $_POST['mobile'];
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Required parameters (fname, lname, email, password or mobile) is missing!";
echo json_encode($response);
}
?>
You should return true or false depending upon whether the user has been found in the database or not, plus there's small syntax error in your isUserExisted() function. Your isUserExisted() function should be like this:
// your code
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
// your code
You have the wrong query Syntax, Use the following:
INSERT INTO users(fname, lname, email, password, mobile, created_at)
VALUES ($fname, $lname, $email, $hash, $mobile, NOW())
When we use a php variable in double qoute then the value of that variable appear, while in a single quote exact that variable name appear. For example:
$x = "hello";
echo "The value is $x"; // The value is hello
echo 'The value is $x'; // The value is $x
Now you can see where you can correct your code.
You need to add quotes in your email and return false if email not found in your database. It is better to use bindParam and rowCount() to count number of rows return from your query
$sql = "SELECT email FROM users WHERE email = :email LIMIT :val ";
$dbh = $this->db->prepare($sql);
$dbh->bindParam(':email', $email, PDO::PARAM_STR);
$dbh->bindParam(':val', 1, PDO::PARAM_INT);
$dbh->execute();
$n = $dbh->rowCount();
if($n>0){
return TRUE;// return true here
}else{
return FALSE;// return false if not found in database
}
I have tried out some code for user registration..every gose fine code works and user data is stored into data base but in register.php file the execution is not entering if($user) statement as the $response of user details..!plz help me out and correct me if am wrong some were...
hear gose the
/DB_Functions.php/
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
/**
* Storing new user
* returns user details
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
$dbh->execute();
$result = $this->db->query($sql);
if ($result) {
// get user details
$id = $this->db->lastInsertId(); //last inserted id
$sql = "SELECT * FROM db_name WHERE email = '$email'";
$result = $this->db->query($sql);
$no_of_rows = $result->fetchColumn();
// returns confirmation message if completed
if ($no_of_rows > 0) {
return "existsandcompleted";
}
}
}
catch (Exception $e) {
$error = 'Error accessing database: ' . $e->getMessage();
}
}
}
?>
and here gose the /register.php/ file were the main problem is...!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['mobile'])) {
// receiving the post params
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$mobile = $_POST['mobile'];
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (fname, lname, email, password or mobile) is missing!";
echo json_encode($response);
}
?>
Problem:
user data is stored into data base but in register.php file the execution is not entering if($user) statement as the $response of user details
Solution:
I'm pretty sure the problem is because of the following line,
$sql = "SELECT * FROM db_name WHERE email = '$email'";
^
I think it should be,
$sql = "SELECT * FROM users WHERE email = '$email'";
^
Moreover, your storeUser() method should be like this:
// your code
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
echo 'Error accessing database: ' . $e->getMessage();
}
return false;
}
// your code