After hashing the password using md5() and store it into database,cant login again - php

i built a login and registration system before,is running well.After I hash the input password using md5()and store it to the database,it cant login anymore.So everyone pls look at my code here,so i can know what goes wrong..here is my code here..
signup.php
include ('config.php');
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=htmlentities($_POST['username']);
$password=htmlentities($_POST['password']);
$email=htmlentities($_POST['email']);
$cpassword=htmlentities($_POST['cpassword']);
//not empty
//at least 3 characters long
//username and password cannot be same
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
else if (strlen($username)<6 ) {
$errors['username2'] = "Username should at least 6 characters long";
}
else if (!preg_match('/^[a-z\d_]{3,20}$/i', $username)) {
$errors['username3'] = "Username should contain letters and numbers only.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
else if (strlen($password) <8) {
$errors['password2'] ="Password should at least 8 characters long";
}
else if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,20}$/', $password)){
$errors['password3'] ="Password should contain at least 1 upper-case,1 lower-case,numbers ";
}
//check the password confirmation
if(empty($cpassword)) {
$errors["cpassword2"] = "Must confirm your password to proceed";
}
if($password != $cpassword){
$errors['cpassword1']="Password do not match";
}
//check whether username or password is same
if($username == $password){
$errors['sameuserpass'] ="Username and password cannot be same";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email3'] ="Please enter a vaild email address";
}
//check the errors
if(count($errors) == 0){
$query=mysqli_query($con,"SELECT * FROM user WHERE Username='$username'");
$query1=mysqli_query($con,"SELECT*FROM user WHERE Email='$email'");
if(mysqli_num_rows($query) > 0) {
$errors['userexist'] ="Username already exists";
}
else if(mysqli_num_rows($query1) > 0){
$errors['emailexist'] = "Email already already exists";
}
else {
//HASHING THE PASSWORD
$password = md5($password);
$queryinsert= "INSERT INTO user(Username,Password,Email) VALUES ('$username','$password','$email')";
mysqli_query($con,$queryinsert);
header("Location:login.php");
}
}
}
login.php
<?php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = htmlentities($_POST['email']);
$password = htmlentities(md5($_POST['password']));
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' ");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows !== 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
if($dbemail === $email&&$dbpassword === $password)
{
$_SESSION['email']="$email";
header('Location:user.html');
exit;
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
?>
I successfully store the password that hashed into the database,but the problem is cant login again although the email address and password is correct.Any idea?

signup.php
include ('config.php');
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$email=mysqli_real_escape_string($con,$_POST['email']);
$cpassword=mysqli_real_escape_string($con,$_POST['cpassword']);
//not empty
//at least 3 characters long
//username and password cannot be same
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
else if (strlen($username)<6 ) {
$errors['username2'] = "Username should at least 6 characters long";
}
else if (!preg_match('/^[a-z\d_]{3,20}$/i', $username)) {
$errors['username3'] = "Username should contain letters and numbers only.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
else if (strlen($password) <8) {
$errors['password2'] ="Password should at least 8 characters long";
}
else if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,20}$/', $password)){
$errors['password3'] ="Password should contain at least 1 upper-case,1 lower-case,numbers ";
}
//check the password confirmation
if(empty($cpassword)) {
$errors["cpassword2"] = "Must confirm your password to proceed";
}
if($password != $cpassword){
$errors['cpassword1']="Password do not match";
}
//check whether username or password is same
if($username == $password){
$errors['sameuserpass'] ="Username and password cannot be same";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email3'] ="Please enter a vaild email address";
}
//check the errors
if(count($errors) == 0){
$query=mysqli_query($con,"SELECT * FROM user WHERE Username='$username'");
$query1=mysqli_query($con,"SELECT*FROM user WHERE Email='$email'");
if(mysqli_num_rows($query) > 0) {
$errors['userexist'] ="Username already exists";
}
else if(mysqli_num_rows($query1) > 0){
$errors['emailexist'] = "Email already already exists";
}
else {
//HASHING THE PASSWORD
$password = md5($password);
$queryinsert= "INSERT INTO user(Username,Password,Email) VALUES ('$username','$password','$email')";
mysqli_query($con,$queryinsert);
header("Location:login.php");
}
}
}
login.php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$password = md5($password);
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' ");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows != 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
if($dbemail == $email && $dbpassword == $password)
{
$_SESSION['email']="$email";
header('Location:user.html');
exit;
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}

This line?
if($dbemail === $email&&$dbpassword === $password)
Shouldn't it be:
if($dbemail == $email&&$dbpassword == $password)
Edit:
And did you change your original password to a md5 hash or re-register
If you need a hash for your Db password - This -> 2aefc34200a294a3cc7db81b43a81873 will change your password to admins
Edit 2:
And I do recommend that you don't use md5 but this instead.
http://php.net/manual/en/function.password-hash.php

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(); }
?>

Problem with bcrpyt hasher when logging in to user account

I created a registration and loging system!
There are no problems with registration.
I enter the desired username, the desired email, the desired password and hit enter,after hitting the enter, I come to the home page.
The problem is when I press the sign out button and when the leave button takes me to the login page,and when i re-enter username and password I get the "incorrect username or password" error.
if (isset($_POST['register'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$repeatpassword = mysqli_real_escape_string($db, $_POST['repeatpassword']);
$username_checker = "SELECT * FROM users WHERE username='$username'";
$email_checker = "SELECT * FROM users WHERE email='$email'";
$name_checker = mysqli_query($db,$username_checker) or die(mysqli_error($db));
$mail_checker = mysqli_query($db,$email_checker) or die(mysqli_error($db));
if(empty($username)){
array_push($errors,"Username is required");
return;
}
if(empty($email)){
array_push($errors,"Email is required");
return;
}
if(empty($password)){
array_push($errors,"Password is required");
return;
}
if(mysqli_num_rows($name_checker) > 0){
array_push($errors,"Username is already recorded in our database");
return;
}
if(mysqli_num_rows($mail_checker) > 0){
array_push($errors,"Email Address is already recorded in our database");
return;
}
if(!preg_match("/^[a-zA-Z ]*$/",$username)){
array_push($errors,"The username is only derived from uppercase and lowercase characters");
return;
}
if(strlen($_POST['username']) < 5){
array_push($errors,"Username must be at least 5 characters long");
return;
}
if(strlen($_POST['username']) > 8){
array_push($errors,"Username must contain a minimum of 5 characters or a maximum of 12 characters");
return;
}
else if(strlen($_POST['username']) > 12){
array_push($errors,"Username must contain a minimum of 5 characters or a maximum of 12 characters");
return;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
array_push($errors,"Invalid email format");
return;
}
if(strlen($_POST['password']) < 8){
array_push($errors,"The password must contain a minimum of 8 or a maximum of 16 characters");
return;
}
else if(strlen($_POST['password']) > 16){
array_push($errors,"The password must contain a minimum of 8 or a maximum of 16
characters");
return;
}
if($password != $repeatpassword){
array_push($errors,"");
return;
}
if(count($errors) == 0){
$password = password_hash($password,PASSWORD_BCRYPT);
$sql = "INSERT INTO users (username, email, password)
VALUES ('$username','$email','$password')";
mysqli_query($db,$sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = " Welcome ".$username." ";
$_SESSION['profile_name'] = $username;
header('location: index.php');
}
}
if (isset($_POST['login'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if(empty($username)){
array_push($errors,"Username is required");
return;
}
if(empty($password)){
array_push($errors,"Password is required");
return;
}
if(count($errors) == 0){
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db,$query);
if(mysqli_num_rows($result) > 0){
if(password_verify($password)){
$_SESSION['username'] = $username;
$_SESSION['success'] = " Welcome Back ".$username;
$_SESSION['profile_name'] = $username;
header('location: index.php');
}
}
else{
array_push($errors,"incorrect username or password");
}
}
}
Everytime you hash your password you create a new string (hash,) so it will never work if you try to match the hashed password with a password that's previously hashed.
Try this:
if (password_verify($_POST['password'], $result['password']))
//True if password is correct
$_POST['password'] is the password from the submitted form in plain text.
$result['password'] is the hashed password in your DB.
And please look into PDO's prepared statements, your code is really dangerous like this.

How to display the username of the current logged in user from database using php [duplicate]

This question already has answers here:
How do I get PHP errors to display?
(27 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
Hi am trying to display the name of user that just logged in, Now when i sign up it works but when i login it does not work, please help.
This it the php code at the top of the index.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
?>
This is the code that was meant to display the name that is in the index.php
<?php echo ucfirst($_SESSION['username']); ?>
This is my server.php
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'register');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM user WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO user (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
// LOGIN USER
if (isset($_POST['login_user'])) {
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM user WHERE email='$email' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
But is like i have discovered that it is because there is no input code that has name="username" in my login.php
yeah, Remember the user is logging in with email and password not username and password, thank you.
This is what your code needs. You will have to enable sessions if you have not done so.
//enable sessions if you have not done so
//session_start();
//$_SESSION['username'] = 'nancy';
$_SESSION['username'] = $results['username'];
You can then echo it as follows
<?php
//enable sessions if you have not done so
//session_start();
echo htmlentities($_SESSION['username']);
?>
hence your code will look like
// LOGIN USER
if (isset($_POST['login_user'])) {
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM user WHERE email='$email' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
//session_start();
// $_SESSION['username'] = 'nancy';
$_SESSION['username'] = $results['username'];
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
Please am sure that you are not using this code in production. Php has a native way of hashing password and you are using deprecated md5.
You can refer on my previous answers on how to write login based on php way.
source As for sql injection, I will suggest that you used prepared statements as its more safer

How to auto login after registration

Like title says I want to log a user in once they successfully registered and don't want them to put username and password again to log in.
Here is registration code
<?php
$name = ((isset($_POST['name']))?sanitize($_POST['name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm = ((isset($_POST['confirm']))?sanitize($_POST['confirm']):'');
$errors = array();
if($_POST){
$emailQuery =$db->query("SELECT * FROM users1 WHERE email = '$email'");
$emailCount = mysqli_num_rows($emailQuery);
if($emailCount != 0){
$errors[] = 'That email already exists in our database.';
}
$required = array('name', 'email', 'password', 'confirm');
foreach($required as $f){
if(empty($_POST[$f])){
$errors[] = 'You must fill out all fields';
break;
}
}
if(strlen($password) < 6){
$errors[] = 'Your password must be atleast 6 characterss';
}
if($password != $confirm){
$errors[] = 'Your password do not match';
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors[] = 'You must enter a valid email';
}
if(!empty($errors)){
echo display_errors($errors);
}else{
//add user to database
$hashed = password_hash($password,PASSWORD_DEFAULT);
$db->query("INSERT INTO users1 (full_name,email,password) values('$name', '$email','$hashed')");
}
?>
And here is how my login structure looks like
<?php
if ($_POST) {
//form validation
if (empty($_POST['email']) || empty($_POST['password'])) {
$errors[] = 'You must provide email and password.';
}
//Validate email
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors[] = 'You must enter a valid email';
}
//Password is more than 6 characters
if(strlen($password) < 6) {
$errors[] = 'Password must be at least 6 characters';
}
// check if email exits in the database
$query = $db->query("SELECT * FROM users WHERE email = '$email'");
$user = mysqli_fetch_assoc($query);
$usercount = mysqli_num_rows($query);
if($usercount < 1){
$errors[] = 'That email does not exist in our database';
}
if (!password_verify($password, $user['password'])) {
$errors[] = 'The password does not match our records. Please try again.';
}
//check for errors
if(!empty($errors)) {
echo display_errors($errors);
}else {
$user_id = $user['id'];
login($user_id);
}
}
?>
And here is login function
function login($user_id){
$_SESSION['SBUser'] = $user_id;
global $db;
$date = date("y-m-d h:i:s");
$db->query("UPDATE users SET last_login = '$date' WHERE id = '$user_id'");
$_SESSION['success_flash'] = 'You are now logged in!';
header('location: index.php');
}
The only thing that you do to indicate that a user is logged in is set $_SESSION['SBUser'] = $user_id;
So in your registration script just do that as well.
<?php
// new code
session_start();
$name = ((isset($_POST['name']))?sanitize($_POST['name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm = ((isset($_POST['confirm']))?sanitize($_POST['confirm']):'');
$errors = array();
if($_POST){
$emailQuery =$db->query("SELECT * FROM users1 WHERE email = '$email'");
$emailCount = mysqli_num_rows($emailQuery);
if($emailCount != 0){
$errors[] = 'That email already exists in our database.';
}
$required = array('name', 'email', 'password', 'confirm');
foreach($required as $f){
if(empty($_POST[$f])){
$errors[] = 'You must fill out all fields';
break;
}
}
if(strlen($password) < 6){
$errors[] = 'Your password must be atleast 6 characterss';
}
if($password != $confirm){
$errors[] = 'Your password do not match';
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors[] = 'You must enter a valid email';
}
if(!empty($errors)){
echo display_errors($errors);
}else{
//add user to database
$hashed = password_hash($password,PASSWORD_DEFAULT);
$db->query("INSERT INTO users1
(full_name,email,password)
values('$name', '$email','$hashed')");
// new code
$_SESSION['SBUser'] = $db->insert_id;
}
?>

Log in returns blank for incorrect password?

I have been using a tutorial for a registration and log in page. Everything is perfect except when a user inputs an incorrect password.
If no password is entered then the stated error is displayed fine.
If the correct password is entered it logs them in.
If the incorrect password is entered it goes to a blank page?!
I want an incorrect password to display a message just like when the wrong username is entered. I've included my entire login.php code:
include('db.php');
if(!isset($_POST['login'])) {
include('form.php');
} else {
if(isset($_POST['user'])&&$_POST['user']==""||!isset($_POST['user'])) {
$error[] = "Username Field can't be left blank";
$usererror = "1";
}
if(!isset($usererror)) {
$user = mysql_real_escape_string($_POST['user']);
$sql = "SELECT * FROM users WHERE user = '$user'";
if(mysql_num_rows(mysql_query($sql))=="0") {
$error[] = "Can't find a user with this username";
}
}
if(isset($_POST['pass'])&&$_POST['pass']==""||!isset($_POST['pass'])) {
$error[] = "password Field can't be left blank";
}
if(isset($error)) {
if(is_array($error)) {
echo "<div class=\"error\"><span>please check the errors and refill the form<span><br/>";
foreach ($error as $ers) {
echo "<span>".$ers."</span><br/>";
}
echo "</div>";
include('form.php');
}
}
if(!isset($error)) {
$suser=mysql_real_escape_string($_POST['user']);
$spass=md5($_POST['pass']);//for secure passwords
$find = "SELECT * FROM users WHERE user = '$suser' AND password = '$spass'";
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())) {
session_start();
$_SESSION['username'] = $suser;
header("Location: loggedin.php");
} else {
echo "<div class=\"warning\"><span>Some Error occured durring processing your data</div>";
}
}
}
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())){
If wrong password is entered, mysql_num_rows(mysql_query($find)) is 0 so it results in die(mysql_error()). But since there is no mysql_error(), you see a blank page.
Try this
$result = mysql_query($find) or die(mysql_error());
if (mysql_num_rows($result) == 1) {
// proceed
} else {
// authentication failed
}
EDIT: This is just for illustration purpose only. Use MySQLi or PDO when dealing with MySQL.
The code is little bit confusing for me, consider using this code.
<?php
include('db.php');
if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['user']);
$password = md5($_POST['pass']);
if(empty($username) || empty($password)) {
echo "Empty username or password.";
} else {
mysql_query("SELECT * FROM `users` WHERE `user` = '$user' AND `password.md5` = '$password'");
if(mysql_num_rows() == 1) {
// login successfull
session_start();
$_SESSION['username'] = $username;
header("Location: loggedin.php");
} else {
echo "Invalid username or password.";
}
}
} else {
include ('form.php');
}
?>

Categories