Password hashing within PHP not working - php

I'm trying to create a password hash in a php file for a mini blog i'm creating, I have got to the stage where new user passwords are being hashed when a user registers, but when I test the new user login, i get an incorrect password error. Here is the code:-
<?php
//require the public header which starts a session and connects to the database
require('header_public.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = db_escape($con, $_POST['username']);
$password = db_escape($con, $_POST['password']);
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM user WHERE username='$username'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$resultPassword = mysqli_query($con, $query) or die(mysqli_error($con));
$count = mysqli_num_rows($result);
//getting the hashed password from the database
while ($row=mysqli_fetch_array($resultPassword)){
$hashPassword = $row['password'];
}
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1 && password_verify($password, $hashPassword)){
$_SESSION['username'] = $username;
//Get the user type for use in other areas of the site
while ($row=mysqli_fetch_array($result)){
$admin = $row['admin'];
}
//assign userid to session array
$_SESSION['admin'] = $admin;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
$fmsg = "Invalid Login Credentials.";
}
}
if (isset($_SESSION['username'])){
//$username = $_SESSION['username'];
echo "Welcome back " . $username;
echo " </br> You will be redirected to the members area in less than 5 seconds";
header( "Refresh:3; summary_page.php");
echo "</br> <a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
Grateful for any steer someone could provide. I think the issue is related to the starting the new session with the username, but can't be sure

Related

how to get customer id from mysql and then to store it in a session variable to use the session variable in another file to retrieve information

I am new to PHP.
I've made a login page and a register page, and I want to store the customer id after successful login or registration on my session variable so that I can use a session variable later in my cart file to retrieve cart details of that customer.The customer id is autoincrementing on the table so I don't take the input from the customer for the customer id.
here are the codes
login.php:
<?php
session_start();
$db=mysqli_connect("localhost","root","Naruto97","musicgallery");
if (isset($_POST['login_btn'])){
$email = mysqli_real_escape_string($db,$_POST['email']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$password=md5($password);
$sql="SELECT * FROM LoginCredentials WHERE email='$email' AND password='$password'";
$result = mysqli_query($db,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['message']="You are now logged in";
$_SESSION['email']=$email;
//Want to store the customer in session variable here after successful login
header("location:home.php");
}
else{
$_SESSION['message']= "Email/Password combination Incorrect";
}
}
?>
register.php:
<?php
session_start();
$db=mysqli_connect("localhost","root","Naruto97","musicgallery");
if (isset($_POST['register_btn'])){
$username = mysqli_real_escape_string($db,$_POST['username']);
$email = mysqli_real_escape_string($db,$_POST['email']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$password2 = mysqli_real_escape_string($db,$_POST['password2']);
if($password==$password2){
$password=md5($password);
$sql = "INSERT INTO LoginCredentials(Username,email,password) VALUES('$username','$email','$password')";
mysqli_query($db, $sql);
$_SESSION['message']="You are now logged in";
$_SESSION['email']=$email;
//Want to store the customer_id here in the session variable after successful registration
header("location:home.php");
}else{
$_SESSION['message']="The passwords do not match";
}
}
?>
cart.php:
<?php
session_start();
$db=mysqli_connect("localhost","root","Naruto97","musicgallery");
if(isset($_POST["add_to_cart"])){
if(isset($_SESSION['email'])){
$album_name = mysqli_real_escape_string($db,$_POST['hidden_name']);
$price = mysqli_real_escape_string($db,$_POST['hidden_price']);
$quantity = mysqli_real_escape_string($db,$_POST['quantity']);
//$customer_id= $_SESSION['customer_id'];
$sql = "INSERT INTO cart(album_name,price,quantity,customer_id) VALUES('$album_name','$price','$quantity','$customer_id')";
mysqli_query($db, $sql);
echo "<script>alert('Added to cart')</script>";
echo "<script>window.location('kpop.php')</script>";
}
else
{
echo "<script>alert('Please Login')</script>";
echo "<script>window.location('kpop.php')</script>";
}
}
?>
To get the last insertid in mysqli use:-
$sql = "INSERT INTO cart(album_name,price,quantity,customer_id) VALUES('$album_name','$price','$quantity','$customer_id')";
mysqli_query($db, $sql);
$_SESSION['customerId']=mysqli_insert_id($db);//gets the last inserted customerid from db
For any further reference you can check in this link.

How fix error with PHP login that ask two times for username and password

When I want to login with this codes in first time I connect to internet, I enter the username and password and push submit and the page get refresh and ask me again for username and password and after enter the username and password for second time the login done!
My code is:
if (isset($_POST['submit']))
{
include ('connect-db.php');
$escapedName = mysql_real_escape_string($_POST['username']);
$escapedPW = mysql_real_escape_string($_POST['password']);
$saltQuery = "select salt from user where username = '$escapedName';";
$result = mysql_query($saltQuery);
$row = mysql_fetch_assoc($result);
$salt = $row['salt'];
$pass=md5($escapedPW);
$password_pro= $pass . $salt;
$query = mysql_query("select * from user where username = '$escapedName' and password = '$password_pro'");
$row=mysql_fetch_array($query);
if($row){
session_start();
$_SESSION['username'] = $escapedName;
$_SESSION['password'] = $pass;
$_SESSION['type'] = $row['user_type'];
$_SESSION['user_id']= $row['user_id'];
$user_id=$row['user_id'];
header('location: panel.php?user_id=$user_id');
}
Place session_start(); at top of the page and also check your form tag's attributes

PHP MYSQL login script session not working

I have a small script to deal with login in to my CMS. The query works fine, but i think i have a problem with SESSIONS, because it redirects to the login page even when the username and password are correct. I have the codes below. Kindly help me resolve this. Thanks in advance.
//checklogin.php....
<?php
include("db/dbconnect.php");
mysqli_select_db($connect, $db);
// username and password sent from signup form
$username = mysqli_real_escape_string($connect, $_POST['username']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$sql = "SELECT username, password FROM login WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($connect, $sql) or die('Error : ' . mysqli_error($connect));
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count == 1)
{
//Register $username, $password and redirect to mainpage"
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("location:about.php");
}
else {
echo "Invalid Username or Password. Please try again.";
echo "<meta http-equiv=Refresh content=5;url=index.php>";
}
?>
//about.php
<?php
//check if user is logged on;
session_start();
if(!isset($_SESSION['username']) )
{
header("location:index.php");
}
?>
You need to start the session before assigning username and password to it. In your "If" condition ($count ==1), you are directly assigning username and password. Put this line before these assignments:
session_start();
So, now your "If" condition becomes this:
if($count == 1)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("location:about.php");
}
I guess, that's what the issue is. Let me know, if it works.
add session_start(); in checklogin.php
This will help you
<?php
session_start(); //missing in checklogin.php
include("db/dbconnect.php");
mysqli_select_db($connect, $db);

Data loss on my login page?

For some reason inputs in my login page don't seem to be getting processes correctly. Correct user inputs are getting returned as invalid (wrong password) having had a look through, I can't see anything particularly obvious. But I can only assume the username or password isn't getting passed for some reason. Would someone more experienced be able to take a look and suggest how I can put it right. Thanks guys. P.S My form is OK, so not included.
function logcon($user, $password )
{
$user = mysqli_real_escape_string($this->conn, $user);
$esc_password = mysqli_real_escape_string($this->conn,$password);
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
$result = mysqli_query($this->conn, $sql);
$row = mysqli_fetch_array($result);
return $row;
}
Login page.
if(isset($_POST['submit'])){
$user=$_POST['user'];
$password=$_POST['password'];
//To ensure that none of the fields are blank when submitting the form if
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = stripslashes($user);
$password = stripslashes($password);
$db1=new dbmember();
$db1->openDB();
$row=$db1->logcon($user, $password);
if($row[0]==1)
{
session_start();
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
$_SESSION['loggedin'] = "true";
header("location:index.php");
}
else
{
print ('<div id="error">Acess denied, wrong username or password?</div>');
}
}
else
{
print ('<div id="error">Enter something!</div>');
}
}
It appears you are using the wrong variable name in your query. I would also suggest you look into doing some sort of hashing and salting of your passwords instead of saving them as plain text.
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
should be
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$esc_password}'";
And your conditional check seems off, you are checking to see if the first field in the results is = 1 instead of seeing if there is a return.
if($row[0]==1)
Should probably be
if($row)

Displaying specific data from mySQL using sessions IDs

I'm trying to display the users first name after they login. They login using their email and password. Though, I would like to collect their first name and display it. Their name is in the same table that the email/password are in. Traditionally, I would use a session ID like this below.
<?php
session_start();
$_SESSION['first'] = $first;
?>
But this typically is for submitted data in a form and is used after the form has been authenticated. My question is, how would I gather data from the mySQl table rather than collecting it from the form and be able to have it has a session ID?... if that makes sense
In your script where they login...just fetch the row and store into session...
Im using PDO, because thats much safer than the deprecated mysql_* functions you use in your login example.....
//start the session
session_start();
//Get their credentials, as follows...
$name = $_POST['username'];
$pass = md5($_POST['password']);
$stmt = $db->prepare("SELECT * FROM admin WHERE username=? AND password=?");
$stmt->execute(array($name, $pass));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0 ) {
//Store users info in a session
$_SESSION["username"] = $row["username"];
$_SESSION["firstname"] = $row["firstname"];
$_SESSION["auth"] = "set";
//Redirect to the user area, where you can echo their name
header ("Location: /app");
//Once in the user area, you can just echo their name like so...
//echo "Hello ".$_SESSION['username'].", Welcome to my site";
} else {
//Redirect back to login if their info is incorrect
header('location: /login');
//whatever your login page name might be...
}
But heres the code, if you don't wanna bother changing your site to utilizing PDO...
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=mysql_real_escape_string($_POST['username']);
$password=md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT id, username, firstname FROM admin WHERE username='$username' and passcode='$password'";
$result=mysql_query($sql);
$row = mysql_fetch_row($result);
if(count($row)>0)
{
$_SESSION['auth'] = 'set';
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
header ("Location: /app");
}
else
{
$error="Your Hngout credentials are incorrect";
}
}
Select the first name (and any other fields you desire) when checking the user name and password match.
if (!isset($_SESSION)) session_start();
$sql=sprintf("SELECT email, firstname FROM users WHERE email=%s AND password=%s",
$_POST["email"], $_POST["password"]);
//You'd better use parameterized query
$result = mysqli->query($sql);
$row = $result->fetch_assoc();
if(mysqli->num_rows > 0)
{
$_SESSION["email"] = $row["email"];
$_SESSION["firstname"] = $row["firstname"];
}
else
{
//operation for no matches
}

Categories