I've put username and md5(password) on my MySQL database. Below is my old login PHP code. I want to add some code that can retrieve my md5 password, because on my old code there is no md5 password. Where is should I add md5(password)?
Here is my full login code:
<?
if ($_POST['username']) {
$username=trim($_POST['username']);
$username = mysql_real_escape_string($username);
$password=trim($_POST['password']);
$password=mysql_real_escape_string($password);
//$password = hash('md5','$password');
if ($password==NULL) {
header("Location: login.php?error=2");
}else{
if($_POST['code']!=$_SESSION['string']){
header("Location: login.php?error=1");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
header("Location: login.php?error=3");
} else {
$data = mysql_fetch_array($query);
if($data['password'] != $password) {
header("Location: login.php?error=4");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username='$username' ") or die(mysql_error());
$row = mysql_fetch_array($query);
$nicke=$row['username'];
$passe=$row['password'];
setcookie("usNick",$nicke,time()+36000);
setcookie("usPass",$passe,time()+36000);
$lastlogdate=time();
$lastip = getRealIP();
$querybt = "UPDATE tb_users SET lastlogdate='$lastlogdate', lastiplog='$lastip' WHERE username='$nicke'";
mysql_query($querybt) or die(mysql_error());
$query = mysql_query("SELECT akhirupgrade from tb_upgrade WHERE username = '$username' and status='upgraded'") or die(mysql_error());
if(mysql_num_rows($query) > 0) {
$row = mysql_fetch_array($query);
$akhir=$row["akhirupgrade"];
$tgl=time();
if ($tgl > $akhir) {
$query = mysql_query("update tb_upgrade set status='', date='', paket='', akhirupgrade='' WHERE username='$username' and status='upgraded'");
$query = mysql_query("update tb_users set account='' WHERE username='$username'");
}
}
header("Location: member.php");
}
}
}
}
}
?>
I would use password_hash() if you running on php 5.5 or greater
When you send the password to the database simply hash it with the function
$password = password_hash(filter_input(INPUT_POST, "password"));
The when you pull the password back out of the database do the same thing to the password they submitted.
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = password_hash(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}
I have not tested this code so there may be errors but hopefully youll get the point :)
PS dont use MD5 please, Very insecure
If you must use md5
$password = md5(filter_input(INPUT_POST, "password"));//Store password
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = md5(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}
Related
I'm trying to make a register/login system. The hashed passwords are saved into database successfully but when i try to login it says "Invalid login" which means it doesn't verify the password. Help me with this, it's my first time using password hash and verify
Signup.php
<?php
include('AdminPanel/connect.php');
$name = $_POST['txt_name'];
$email = $_POST['txt_email'];
$password = password_hash($_POST['txt_pass'], PASSWORD_DEFAULT);
$radioVal = $_POST['Gender'];
if($radioVal == "Male")
{
$radioVal = "Male";
}
else if ($radioVal == "Female")
{
$radioVal = "Female";
}
$queryget = mysqli_query($con,"SELECT Email FROM signup WHERE Email='$email'") or die ("Query didnt work");
$row = mysqli_fetch_array($queryget);
$emaildb = $row['Email'];
if($emaildb!=$email){
echo"success";
$insert = mysqli_query($con,"insert into signup (Name,Email,Password,Gender) values ('$name','$email','$password','$radioVal')");
}else{
echo"Email already exists";
}
?>
Login.php
<?php
include('AdminPanel/connect.php');
session_start();
$email = $_POST['txt_email'];
$password = $_POST['txt_pass'];
$info = mysqli_query($con,"select count(*) from signup where Email = '$email' and Password = '$password'");
$row = mysqli_fetch_array($info);
if (($row[0] > 0) && password_verify($password, $row['Password']))
{
$_SESSION['txt_email']=$email;
echo "success";
}
else
{
echo "Invalid login<br>Please re-enter your credentials";
}
?>
You're selecting count(*):
$info = mysqli_query(
$con, "select count(*) from signup where Email = '$email' and Password = '$password'"
);
But then referencing a field:
$row['Password']
You need to select (at least) the field, but leave out the condition on password because the password you get won't match what's in the database:
$info = mysqli_query(
$con, "select * from signup where Email = '$email'"
);
Also, don't do that, because SQL injection.
i have problem with login , when i entered correct username and wrong password the result should not allow me to login but in my case if the username correct and the password wrong it's allow me to login to the application.
here is my login script
<?PHP
include_once("conn.php");
$user= $_POST['userName'];
$password = mysqli_real_escape_string($_POST['password']);
$qr="select password from user where userName='$user'";
$res=mysqli_query($con, $qr);
while($row=mysqli_fetch_array($res)){
$pass=$row[0];
}
$saltQuery = "select salt from user where userName = '$user'";
$result = mysqli_query($con , $saltQuery);
while($row=mysqli_fetch_array($result)){
$salt = $row[0];
}
$saltedPW = $password . $salt;
$hashedPW = hash('md5', $saltedPW);
if($pass==$hashedPW){
$query = "SELECT userName, password FROM user WHERE userName = '$user' AND password = '$hashedPW'";
$result = mysqli_query($con, $query);
if($result->num_rows > 0){
echo"success login ";
} else{
echo"failed login ";
}
Try to do something that for login page.
<?php
include("config.php");
if(isset($_POST['submit']))
{
echo $username= $_POST['username'];
echo $password= $_POST['password'];
$username = addslashes($username);
$password = addslashes($password);
$username = mysqli_real_escape_string($link, $username);
$password = mysqli_real_escape_string($link, $password);
$pass= md5($password);
$seladmin ="SELECT id,UserName,Password FROM login WHERE UserName='$username' && Password='$pass'";
$SelRecAdmin = mysqli_query( $link,$seladmin );
$row = mysqli_fetch_array($SelRecAdmin);
$tot_num_row=mysqli_num_rows($SelRecAdmin);
if($tot_num_row >0)
{
$_SESSION['adminid']=$row['id'];
$_SESSION['adminunm'] = $row['UserName'];
header('location:home.php');
exit;
}
else
{
$_SESSION['msg']= 'Invalid username or password';
header('location:index.php');
exit;
}
}
?>
I have developed a solution for your question. I didn't run it, if you get any syntax errors kindly fix it by yourself.
**Make sure you don't have same Username in your code, Otherwise it'll show success message if if you enter wrong password. (As per your code ).
But the following code should give you the expected results even if you have multiple entries with same username. **
<?PHP
include_once("conn.php");
$user= $_POST['userName'];
$password = mysqli_real_escape_string($_POST['password']);
$password = hashIt($password,$user);
$res=mysqli_query($con,"select * from user where userName='".$user."' AND password='".$password."'");
if(mysqli_num_rows($res) == 1){
echo "Login Successfull";
}else{
echo "Invalid Username/Password";
}
function hashIt($password,$user){
$result = mysqli_query($con,"select salt from user where userName = '".$user."'");
// No need to check other things, if query fails / no records found anyway it'll show login failure message.
while($row=mysqli_fetch_array($result)){
$salt = $row['salt'];
}
$saltedPW = $password . $salt;
return hash('md5', $saltedPW);
}
?>
I am trying to verify the hashed password in my database using the password_verify() function but it doesn't seem to be working. Any help please.
<?php
include("config.php");
include("vendor/password.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_real_escape_string($db , $_POST['umail']);
$password = mysqli_real_escape_string($db , $_POST['upassword']);
$userQuery = "SELECT username, password FROM users WHERE username = '$username' AND password='$password'";
$result = mysqli_query($db ,$userQuery);
$queryRow = mysqli_fetch_array($result , MYSQLI_ASSOC);
$queryCount = mysqli_num_rows($result);
$verifyPassowrd = password_verify($_POST['upassword'] , $queryRow[2]);
if ($verifyPassowrd){
header("Location:home.php");
}else{
echo "Username Or Password is invalid";
}
mysqli_close($db);
}
?>
Your password is hashed in your database.
In your query you include a non-hashed password, so the results of the query will be an empty set.
No need to have the password in the WHERE clause of your query, because you want to check the returned hash in the password_verify function.
Updated snippet (I also fixed the typo's):
<?php
include("config.php");
include("vendor/password.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_real_escape_string($db , $_POST['umail']);
$userQuery = "SELECT username, password FROM users WHERE username = '$username'";
$result = mysqli_query($db, $userQuery);
$queryRow = mysqli_fetch_array($result, MYSQLI_ASSOC);
$queryCount = mysqli_num_rows($result);
$verifyPassword = password_verify($_POST['upassword'], $queryRow['password']);
if ($verifyPassword){
header("Location:home.php");
}else{
echo "Username Or Password is invalid";
}
mysqli_close($db);
}
?>
I have created a database with a table (UserPass) which essentially stores Usernames and Passwords.
Now in my form I want to ask a user to input his username and password and while testing this, I realized that I can input any username from the database and any password to login.
Is it possible to select in the SQL query the password that is in the same line as the username?
I tried something like:
$username = $_POST['username'];
$sql = "SELECT Password FROM UserPass WHERE Username = $username";
But the following mysqli_query failed:
$query = mysqli_query($cxn, $sql);
So here is the entire action.php script:
<?php
include "info.php";
include "god.php";
session_start();
if($_POST['god'] == $god)
{
header( "refresh:0;url=../web.html" );
}
else if(empty($_POST['god']))
{
}
else
{
echo "Can't you read: DON'T TRY!!!!!!!";
exit();
}
$cxn = mysqli_connect($host, $user, $password, $dbname) or die("Go");
//check username
$userI = $_POST["username"];
$userSql = "SELECT Username FROM UserPass ";
$result = mysqli_query($cxn, $userSql) or die("Query failed!");
while($line = mysqli_fetch_assoc($result))
{
extract($line);
foreach ($line as $key => $val)
{
if($_POST['username'] == $val)
{
//check for password
$username = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT Password FROM UserPass";
$passres = mysqli_query($cxn, $sql) or die("Request cannot be handled now.");
while ($passline = mysqli_fetch_assoc($passres))
{
extract($passline);
foreach ($passline as $k => $v)
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
}
else
{
session_destroy();
}
}
}
}
}
}
/*
if($userI == $line['Username'])
{
//check for password
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$res = mysqli_query($cxn, $sql) or die("Pass query failed");
$passline = mysqli_fetch_assoc($res);
if($pass == $passline['Password'])
{
header( "refresh:4;url=../web.html");
session_start();
echo "Login succesful, session started, session id: ";
}
}
*/
/*
if($_POST['username'] == $val)
{
//check for password
$b = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$passres = mysqli_query($cxn, $sql);
$passline = mysqli_fetch_row($passres);
foreach ($passline as $k => $v )
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
session_start();
}
}
}
*/
/*
else
{
print("Destroying Laptop...US Government...Destroying Laptop...\n");
exit();
}
*/
?>
You just need to check if there is a record that contains both username and password of the same user:
$password = mysqli_real_escape_string($password);
$username = mysqli_real_escape_string($username);
$sql = "SELECT Password FROM UserPass WHERE Username = '$username' AND Password = '$password'";
if there is 1 such result, it is OK.
BTW, you should not store passwords in plain text - instead use one-way hashing function and compare only the hashes of the passwords.
Your SQL query should contain an 'AND' like this:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM UserPass WHERE username = '{username }' AND password = '{$password}' LIMIT 1";
$query = mysqli_query($link, $sql);
if ($query && mysqli_num_rows($query)>0) {
//user is authenticated
}
?>
By using the logical operator AND your query must match two conditions to give you an answer. That conditions should be known only by the users.
Also please do not store the password field as clear text in database. It's not safe. You should use sha1 hash. For more information about this please take a look here http://en.wikipedia.org/wiki/SHA-1
I have successfully used Phpass to hash registered users passwords and store them in a database, now i am stuck on the login how to check the sumbitted username and password, checking the username exists in the database then checking the hashed password against the one given.
Any help much appreciated!!! Thankyou!
This is my code:
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
require("PasswordHash.php");
$hasher = new PasswordHash(8, false);
$username = $_POST['username'];
$password = $_POST['password'];
// Passwords should never be longer than 72 characters to prevent DoS attacks
if (strlen($password) > 72) { die("Password must be 72 characters or less"); }
$query = "SELECT * FROM user WHERE username = '$username'";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows = 1) {
$res = mysql_query("SELECT password FROM user WHERE username = '$username'");
$row = mysql_fetch_array($res);
$hash = $row['password'];
$password = $_POST['password'];
if ($hasher->CheckPassword($password, $hash)) { //$hash is the hash retrieved from the DB
$what = 'Authentication succeeded';
} else {
$what = 'Authentication failed';
}
} else {
echo "No Such User";
include 'login.php';
exit();
}
echo "$what\n";
echo "<br />";
echo "$hash";
?>
THIS IS MY WORKING CODE FOR BENEFIT OF OTHERS:
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
require("PasswordHash.php");
$hasher = new PasswordHash(8, false);
$username = $_POST['username'];
$password = $_POST['password'];
// Passwords should never be longer than 72 characters to prevent DoS attacks
if (strlen($password) > 72) { die("Password must be 72 characters or less"); }
$query = "SELECT * FROM user WHERE username = '$username'";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows = 1) {
$res = mysql_query("SELECT * FROM user WHERE username = '$username'");
$row = mysql_fetch_array($res);
$hash = $row['password'];
$password = $_POST['password'];
if ($hasher->CheckPassword($password, $hash)) { //$hash is the hash retrieved from the DB
$what = 'Authentication succeeded';
} else {
$what = 'Authentication failed';
}
} else {
echo "No Such User";
include 'login.php';
exit();
}
echo "$what\n";
echo "<br />";
echo "$hash";
?>
Here's how phpass works: When you save the user's password (when they create it) you hash it before saving, like so:
$hash_iterations = 30;
$portable_hashes = FALSE;
$hasher = new PasswordHash($hash_iterations, $portable_hashes);
$hash_value = $hasher->HashPassword($actual_password);
Then save $hash_value in the database as the user's password. When you go to validate the user, look up the user by username. If found, compare the actual password from the database (stored hash) with a hash of what the user entered:
// $stored_hash is the value you saved in the database for this user's password
// $user_input is the POST data from the user with the actual password
$valid_password = $hasher->CheckPassword($user_input, $stored_hash);
Make sure to initialize the PasswordHash class the same way each time, with the same values for $hash_iterations and $portable_hashes, or the comparison won't work correctly.