Check for duplicate user from MySQL database [duplicate] - php

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
I would like to check for duplicates in a MySQL database when registering an user.
If the user exists display an error to that effect, else sign up.
I know there's a few questions like this but I found it hard to paste any of them into my code.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//two passwords are the same
if($_POST['password'] == $_POST['confirmedpassword']) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$sql = "INSERT INTO members(username, password)"
. "VALUES ('$username','$password')";
//if query is successful redirect to login.php
if ($mysqli->query($sql) === true)
$_SESSION['message'] = 'Success';
header("location: login.php");
} else {
$_SESSION['message'] = "User couldnt be added";
}
} else {
$_SESSION['message'] = "Passwords dont match";
}
}

I added some salt to your md5 password to make it seem more secure, but actually this solution is not secure either. To encrypt passwords in PHP it is advisable to use the password_hash() function like this:
$pass = password_hash($password, PASSWORD_BCRYPT);
password_hash() creates a new password hash using a strong one-way hashing algorithm.
and later test it with password_verify():
password_verify ( $passToTest , $knownPasswordHash );
more the functions here: http://php.net/password-hash, http://php.net/password-verify.
Also, since you are using MySQLi consider using prepared statements, or at least properly filter your input data before applying it to the database.
More on prepared statements: http://php.net/prepared-statements.
I added a select statement to check if the user already exists in the table prior to adding the user to the database.
When using header() to change page location put exit() or die() in the next line of code if you want to exit immediately and don't want other code to execute.
Here is your code with the addition of the select statement:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//two passwords are the same
if($_POST['password'] == $_POST['confirmedpassword'])
{
$username = $mysqli->real_escape_string($_POST['username']);
// You might consider using salt when storing passwords like this
$salt = 'aNiceDay';
$password = md5(md5($_POST['password'].$salt).$salt);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$sql = "SELECT `username` FROM members WHERE `username` = '".$username."'";
$result = $mysqli->query($sql);
if(mysqli_num_rows($result) > 0)
{
echo 'User exists.';
// Do something.
}
else
{
$sql = "INSERT INTO members(username, password) VALUES ('".$username."','".$password."')";
if($mysqli->query($sql) === true)
{
$_SESSION['message'] = 'Success';
header("location: login.php");
// Important to put exit() after header so other code
// doesn't get executed.
exit();
}
else
{
$_SESSION['message'] = "User couldn't be added";
echo "User couldn't be added.";
}
}
}
else
{
$_SESSION['message'] = "Passwords dont match";
}
}
?>

So you can check that the user exists or not.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//two passwords are the same
if($_POST['password'] == $_POST['confirmedpassword']) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//Check user
$CheckUserIsExist = mysqli->query("SELECT uid FROM members WHERE username='$username'");
if(mysqli_num_rows($CheckUserIsExist)==0 ){
$sql = "INSERT INTO members(username, password)"
. "VALUES ('$username','$password')";
//if query is successful redirect to login.php
if($mysqli->query($sql) === true)
$_SESSION['message'] = 'Success';
header("location: login.php");
}
} else{
echo 'This username is already in use. Please use different username';
}
else{
$_SESSION['message'] = "User couldn't be added";
}
}
else{
$_SESSION['message'] = "Passwords don't match";
}

Related

How to use the encrypt password for login php [duplicate]

This question already has answers here:
How to use PHP's password_hash to hash and verify passwords
(5 answers)
Closed 1 year ago.
At first I am using md5 for hashing but then I learn that password_hash is more secured, but when I tried to use it in my website it wont work. I've tried putting the code password_verify everywhere.
When I'm trying to login it just giving me an error of password/ email combination is wrong even if it is correct. I also get the error for the password verify but when I put the correct credentials it's still giving me the error message
This is my login code
<?php
function login(){
global $db, $email, $errors;
// grab form values
$email = e($_POST['email']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($email)) {
array_push($errors, "Email is required");
}else {
$email = hsc($_POST["email"]);
}
if (empty($password)) {
array_push($errors, "Password is required");
}else{
$password = hsc($_POST["password"]);
}
// attempt login if no errors on form
if (count($errors) == 0) {
$query = "SELECT * FROM accounts WHERE email='$email' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (password_verify($password, $_POST["password"])) {
array_push($errors, "Wrong password");
}
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/admin.php');
exit(0);
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
exit(0);
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
This is my register code (There are all in the same file functions.inc.php)
function register(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $username, $email;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password']);
$password_2 = e($_POST['re-password']);
//check email if already exist on database
$check = "SELECT * FROM accounts WHERE email='$email'";
$res_e = mysqli_query($db, $check);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Name is required");
}elseif (!preg_match("/^[a-zA-Z]+( [a-zA-Z]+)*$/",$username)) {
array_push($errors, "Only letters and one space only");
}else{
$username = hsc($_POST["username"]);
}
if (empty($email)) {
array_push($errors, "Email is required");
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "The email is invalid");
}elseif (mysqli_num_rows($res_e) > 0) {
array_push($errors, "The email already taken");
}else{
$email = hsc($_POST["email"]);
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}elseif ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}else{
$password_1 = hsc($_POST["password_1"]);
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$hashpassword = password_hash($password_1, PASSWORD_DEFAULT);;//encrypt the password before
saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO accounts (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$hashpassword')";
mysqli_query($db, $query);
$_SESSION['add'] = "Added successfully";
header('location: users.php');
exit(0);
}else{
$query = "INSERT INTO accounts (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$hashpassword')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['add'] = "You are now logged in and thank you!";
header('location: index.php');
exit(0);
}
}
}
I don't know if this is also the reason that the login is not working but it is better that I put it in. This is the code for function hsc() and e()
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
// htmlspecialchars the inputs data
function hsc($val) {
$val = htmlspecialchars($val);
return $val;
}
Here is the data base photo
(By far the simplest method...)
Try this example. It uses Argon2, which is by far the safest encryption method (AFAIK)
Note that it randomly generates a different string when run, so using password_verify is mandatory unlike using sha-256 to look up the password in the database
<?php
$pwd = password_hash("my password goes here", PASSWORD_ARGON2I);
// Use $_POST instead
echo $pwd;
?>
And to verify your password:
if(password_verify($_POST['password'], $row["password"])) {
// Your code here...
}
Also, use PDP PDO, it's much safer against SQL injection attacks
<?php
$db = new PDO('mysql:host='.$servername.';dbname='.$dbname.';charset=utf8mb4', $username, $password);
try {
$query = "SELECT * from `login` WHERE `username`=:username OR `email` =:usernamea";
$stmt = $db->prepare($query);
$stmt->bindParam('username', $username, PDO::PARAM_STR);
$stmt->bindParam('usernamea', $username, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($count == 1 && !empty($row)) {
$auth_email = $row['email'];
$auth_pwd = $row['password'];
if(password_verify($_POST['password'], $auth_pwd)) {
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
$_SESSION['name'] = htmlspecialchars($row['name']);
}
else {
echo 'Invalid';
}
}
else {
echo 'Invalid';
}
}
catch (PDOException $e) { echo "Error : ".$e->getMessage(); }
?>

PHP - password_hash() verification

The following code should be straight forward and simple, the insert into the db on signup creates a hash, but later when I try to login with the same password the hash it is creating isn't matching up to what is in the database (I had print_r's throughout to verify). Can someone see if I'm just overlooking something dumb?
session_start();
require_once("login.php");
$error = "";
$email = "";
$password = "";
if (isset($_GET['logout'])) {
unset($_SESSION['id']);
setcookie('id', '', time() - 60*60);
$_COOKIE['id'] = "";
} else {
if (isset($_SESSION['id']) or isset($_COOKIE['id'])) {
header("Location: loggedinpage.php");
}
}
if (isset($_POST["submit"])) {
$link = mysqli_connect($hn, $un,$pw,$db);
if($link->connect_error) die("Fatal Errror.");
if (!$_POST["email"]) {
$error .="An email address is required<br>";
}
if (!$_POST["password"]) {
$error .="A password address is required<br>";
}
if ($error != "") {
$error= "<p>There were error(s) in your form:</p>".$error;
} else {
if ($_POST['signup'] == 1) {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link,$_POST['password']);
$query = "SELECT id FROM `users` WHERE email = '".$email."' LIMIT 1";
$result=$link->query($query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is taken.";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO `users`(`email`,`password`) VALUES ('".$email."', '".$hashedPassword."')";
if (!mysqli_query($link,$query)) {
$error = "<p>Could not sign you up, please try again later</p>";
} else {
$_SESSION['id'] = mysqli_insert_id($link);
if(isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', mysqli_insert_id($link), time()+60*60*24);
}
header("Location: loggedinpage.php");
}
}
} else {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
$query = "SELECT * FROM users WHERE email = '".$email."' LIMIT 1";
$result = $link->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if ($email == $row['email'] and password_verify($password,$row['password'])) {
if (isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', $row['id'], time()+60*60*24);
header("Location: loggedinpage.php");
}
} else {
$error = "Incorrect Username/Password combination";
}
}
}
}
}
Although it's tucked away at the end of a paragraph, PHP documentation does say that "it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice)."
The current default algorithm, bcrypt, generates hashes that are 60 characters long. If your database column cannot hold at least this many characters, your hashes will be truncated and verification will fail.
You've got a few other problems as well:
You're modifying the password before generating the hash (with mysqli_real_escape_string())
You're not using prepared statements
You appear to be relying on cookies for authentication. Cookies are user-generated data, they are not to be trusted! This is why PHP provides session support, because the data is stored on the server.
You should not be checking for an existing email address using a query, instead you should have a unique index set on the email column in the database.
try
if(password_verify($password, (string)$row->password)){
//Your Code
}
because of password_verify function return Boolean only true or false
And
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
Only add once when you Insert to Sql (new user)

password_verify for hashed password

I have admin page that will insert user id, password, role. The password will be hash after admin insert new user. It work well but when I try to login using the hash password, it will pop up "invalid user or password". Maybe because I put the password_verify coding in the wrong place. Can someone help me!!
Below is my coding
login.php
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "","company");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection, "select * from login where password='$password' AND username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$pwdCheck = password_verify($password,$row['password']); $_SESSION['user']=array(
'username'=>$row['username'],
'password'=>$row['password'],
'role'=>$row['role']
);
$role=$_SESSION['user']['role'];
//Redirecting User Based on Role
switch($role){
case 'user':
if ($pwdCheck == true)
header("location: index.php"); // Redirecting To Other Page
break;
case 'admin':
if ($pwdCheck == true)
header("location: adminindex.php"); // Redirecting To Other Page
break;
}
}
else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
?>
crud_include.php (admin insert new user)
if (isset($_POST['save'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$role = $_POST['role'];
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_query($db, "INSERT INTO login (username, password,role) VALUES ('$username', '$hashedPwd','$role')");
$_SESSION['message'] = "Successfully saved!";
header('location: crud.php');
}
the database (the hash work well but i cannot login using this user
Change your select query : In a where case use only username
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$query = mysqli_query($connection, "select * from login WHERE username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
if (password_verify($password, $row['password'])) {
echo 'Password is valid!';
if($role=$_SESSION['user']['role'] == 'user'){
header("location: index.php");
}elseif($role=$_SESSION['user']['role'] == 'admin'){
header("location: adminindex.php");
}
} else {
$error = "Password is invalid";
}
}else{
$error = "Username is invalid";
}
?>
Hope it will help you.
Here the the link for the hash password verified

User Authentication Password Hashes [duplicate]

This question already has answers here:
Where to put password_verify in login script?
(2 answers)
Closed 7 years ago.
Okay so i'm trying to make a basic user authentication system. Well I already made it. But what im trying to do now is check the users password against a hash. I'm using $hash = password_hash($password, PASSWORD_DEFAULT); but for the login page I want to check the users password with the hashed password in the database so they can login. How can I do this?
Register.php:
<?php
include('config.php');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function mres($input){
if (get_magic_quotes_gpc()){
$input = stripslashes($input);
}
return mysqli_real_escape_string($conn, $_POST['$input']);
}
$email=mysqli_real_escape_string($conn, $_POST['email']);
$username=mysqli_real_escape_string($conn, $_POST['username']);
$password=mysqli_real_escape_string($conn, $_POST['password']);
$hash = password_hash($password, PASSWORD_DEFAULT);
$query = $conn->query("select * from users where username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
echo "User already exist redirecting in 5 seconds!";
} else {
$sql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$hash', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
header("Location: ../index.php");
?>
Login.php:
<?php
session_start();
include('config.php');
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['userid']) || empty($_POST['passid'])) {
$error = "Username or Password is invalid";
}
else
{
$user=mysqli_real_escape_string($conn, $_POST['userid']);
$pass=mysqli_real_escape_string($conn, $_POST['passid']);
$hash = password_hash($pass, PASSWORD_DEFAULT);
$passv = password_verify($pass, $hash);
$query = $conn->query("select * from users where password='$passv' AND username='$user'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
$_SESSION['username']=$user;
$_SESSION['checklogin']== true;
header("location: ../profile.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($conn);
}
}
?>
(Yes i know i added that function there that im not using in register. Its for future use im saving it for now. I have plans for it.)
Select the password from database using the username. Get the hash password from the database and use password_verify(inputPassword,hashPassword) with an if statement.

Why wont this check to see if a user exists?

I'm performing a query to check if a user exists before adding it to the database. If that result comes back then die and echo 'username already exists' but if it comes back empty then add the new user to the database.
For some reason it just adds a new user to the database anyway.
//If post was
if (isset($_POST['submit'])) {
// Check if username is blank
if (!isset($_POST['username']) || empty($_POST['username'])) {
echo "Username was blank<br />";
die();
} else {
$username = mysqli_real_escape_string($connection, $_POST['username']);
}
// Check if password is blank
if (!isset($_POST['password']) || empty($_POST['password'])) {
echo "Password was blank<br />";
die();
} else {
$password = mysqli_real_escape_string($connection, $_POST['password']);
$password2 = md5($password);
//echo $password;
}
// Check if email is blank
if (!isset($_POST['email']) || empty($_POST['email'])) {
echo "Email was blank<br />";
die();
} else {
$email = mysqli_real_escape_string($connection, $_POST['email']);
//$password = md5($password);
//echo $password;
}
//Check to see if username alread exsists
$query_check = "SELECT * FROM users WHERE user = '$username' LIMIT 1";
$result_check = mysqli_query($connection, $query_check);
if(count(mysqli_fetch_array($result_check)) === 1) {
echo "Username exists.";
die();
} else {
$query = "INSERT INTO users (user, pass, email) VALUES ('$username','$password2','$email');";
$result = mysqli_query($connection, $query);
if($result){ // returned TRUE, e.g. in case of a DELETE sql
$_SESSION["username"] = $username;
header("Location: ../profile.php");
} else { // returned FALSE
//echo "Error: " . mysqli_error($connection);
echo "Error during register <a href='../register.php'>Back To Register</a>";
die();
}
}
} else {
header("Location: ../index.php");
}
After taking a few minutes testing your code, found that you're using the wrong function.
mysqli_fetch_array():
Fetch a result row as an associative, a numeric array, or both
You're trying to fetch an associative array.
As opposed to mysqli_num_rows():
Gets the number of rows in a result
Replace (and which seems to have been taken from FĂ©lix's answer)
if(count(mysqli_fetch_array($result_check)) === 1)
with
if(mysqli_num_rows($result_check) == 1)
or
if(mysqli_num_rows($result_check) > 0)
Your original post contained:
if(mysqli_fetch_array($result_check) === 1)
which still stands to be the wrong method.
I even said to use mysqli_num_rows() in a comment, but nothing was said about it:
if(mysqli_num_rows($result_check) >0) and make sure $username is defined. We don't know how/where if it is even defined.
Now, if THAT fails, then your form element isn't named, and/or something else in your form is failing you.
I.e.: <input type="text" name="username">
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Regarding using MD5.
That isn't considered safe to use anymore, as far as password hashing goes.
That technology is old and is considered broken.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Pulled from ircmaxell's answer which uses PDO with prepared statements and password_hash():
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
Footnotes:
I noticed you are using headers.
You should add exit; after each header. Otherwise, your code may want to continue executing.
header("Location: ../profile.php");
exit;
and do the same for the other one also.
You're also using sessions. session_start(); isn't present in your posted and will fail if it isn't included; an insight.
here
if(mysqli_fetch_array($result_check) === 1) {
the value returned by mysqli_fetch_array won't be an integer but an array. You seem to want to count it:
if(count(mysqli_fetch_array($result_check)) === 1) {
In the case somehow two users would have been inserted for whatever reason, checking if count is greater than 0 may prevent a third one being inserted:
if(count(mysqli_fetch_array($result_check)) > 0) {

Categories