I'm trying to do a simple login, which compares the input of the ID and password by the user with the data in the database
//getting the inputs
$checkid = $_POST["id"];
$checkpassword = md5($_POST["pass"]);
//getting the id and password of the id and password of the inputs
$query = "SELECT id, password FROM login WHERE id=$checkid AND password=$checkpassword";
$res = mysqli_query($link, $query);
$nres = mysqli_num_rows($res);
//$nres should be 0 if the user inputs the right id but the wrong password
//or viceversa, the only way that it $nres!=0 is that both inputs match the db, right?
if ($nres == 0) {
header('Location: http://localhost:8888/login/login_fail.php');
else
header('Location: http://localhost:8888/profile/profile.php');
exit();
it doesn't work, even if i put the right ID and the password that are on the database it will redirect to login_fail.php.
Note: it does work if i do it just with he ID and take out of the query " ,password" "AND password = $checkpassword". Help
Add quotes to your variables:
"SELECT id, password FROM login WHERE id='$checkid' AND password='$checkpassword'"
^ ^ ^ ^
Sidenote: Don't use md5, it's now insecure to use as password storage.
For password storage, either use bcrypt or PHP's password() function.
And see this article also
Also noted in comments by others, use mysqli_real_escape_string():
$checkid=mysqli_real_escape_string($link,$_POST['id']);
Try the query:
$query = "SELECT id, password FROM login WHERE id='".$checkid."' AND password='".$checkpassword."'";
Related
i'm trying to make a log in form where the password where encrypted in oracle DB, i can't decrypt the password in my select statement in php. when i put the correct password the error message pop out and when i try to put the encpryted password it proceeds to log in ,
$strSQL = "SELECT USER_ID, PASS_WORD FROM VW_SMF_USERS WHERE USER_ID =
'".trim($_POST['txtUseremail'])."'
AND PASS_WORD = '".trim($_POST['txtUserpassword'])."'";
$objParse = oci_parse ($objConnect, $strSQL);
oci_execute ($objParse,OCI_DEFAULT);
$objResult = oci_fetch_array($objParse);
As i can understand your current scenario, you have hashed password in database, and you are querying user_input password direct to database, that is why application logged in with hash but not with plain text password.
You need to encrypt user_input password first in desired hash (md5,sha), example md5:
"SELECT USER_ID, PASS_WORD FROM VW_SMF_USERS WHERE USER_ID =
'".trim($_POST['txtUseremail'])."'
AND PASS_WORD = '".md5($_POST['txtUserpassword'])."'";
For some reasons, I don't know if I am really getting the hashed password from the database or if I am comparing it right to the inputted password. I have successfully tested my registration with the password_hash method and I am seeing the hashed password in the database.
Should I also hash the inputted password to be compared to the hashed password from the database? Or my query is just wrong? Please help!!! Thanks!
<?php
require "../connection.php";
session_start();
if(isset($_POST['login'])) {
$username = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = stripslashes($_POST['password']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$query = mysqli_query ($conn, "SELECT * FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));
$reader = mysqli_num_rows($query);
if ($reader == 1) {
$passwordQuery = mysqli_query ($conn, "SELECT password FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));
$row = mysqli_fetch_array($passwordQuery);
$hashedPasswordFromDb = $row['password'];
if (password_verify($password, $hashedPasswordFromDb)) {
$query = mysqli_query ($conn, "SELECT id, student_number FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));
$row = mysqli_fetch_array($query);
$id = $row['id'];
$student_number = $row['student_number'];
$sesData = array('id' => $id, 'student_number', $student_number);
$_SESSION['ses_account'] = $sesData;
mysqli_query ($conn, "UPDATE admin SET lastLogin=NOW() WHERE student_number='$student_number'");
header("location: dashboard.php");
} else {
$msg="User not recognized. Please try again.";
urlencode($msg);
header("location: ../index.php?errmsg=$msg");
}
} else {
$msg="User not recognized. Please try again.";
urlencode($msg);
header("location: ../index.php?errmsg=$msg");
}
}
?>
I assume you are storing hashed passwords into the database (that's good)
but here:
$query = mysqli_query ($conn, "SELECT * FROM admin WHERE username='$username' AND password='$password'") OR DIE(mysqli_error($conn));
you are fetching the user comparing a hashed password with a plain-text one. So the query will never return any row/user.
Here is how you should proceed to implement a very basic system for 1 registering a user and 2 check for login.
First of all use prepared statements instead of sanityzing input and then injecting strings into the query. You'll end up with safer and more readable code.
1 When you register a new user store the username and the hashed (and possibly salted) password into the db.
2 When you check for login, hash/elaborate the plain text password you get as input (with the same process you implemented when performing registration) then make a single SELECT to get the user by username and finally check hashed password matches.
Assuming you're at least on PHP 5.5 use password_hash and password_verify to hash the password (password_hash) and check a plaintext password with a hashed one (password_verify)
Further reading here: Secure hash and salt for PHP passwords
I've been modifying my code but I still can't log in... I have a MySQL database with a database called "users" with a table called "Users" and the following rows "UserNameID", "userName" and "password". I have created just an entry in order to test that:
+------------+----------+-----------+
| UserNameID | userName | password |
+------------+----------+-----------+
| 1 | root | pass |
+------------+----------+-----------+
Here my code:
<!DOCTYPE html>
<?php session_start(); ?>
<html>
<head>
<title>File1</title>
</head>
<body>
<?php
$DB_connection = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($DB_connection));
function SignIn() {
$usr = $_POST['user'];
$pw = $_POST['pwd'];
if(!empty($usr)) {
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."; } }
}
SignIn();
mysqli_close($DB_connection);
?>
</body>
</html>
When I introduce a wrong password or username, it gives me "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...". However, it throws me the same when I put the correct password and username. What is wrong in my code?
Thanks a lot!
There numerous issues here. There are scoping issues, you are using the wrong methods, it's unsafe.
First off, these 2 lines:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
That's not how you query a database. You only need to call either mysql_query or mysqli_query depending on what API you are using. You are using MySQLi in this case, so do this:
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
$result = mysqli_query($DB_connection,$query);
Second, your SignIn function can't access the $DB_connection variable, it's out of scope. You need to pass it in:
function SignIn($DB_connection){
}
SignIn($DB_connection);
Third, this code is very unsafe! Never use $_POST directly in an SQL query like that. You should never be concatenating variables into an SQL string, you should use prepared statements.
// Don't use "SELECT *", use the fields you want
$query = mysqli_prepare($DB_connection, 'SELECT user_id FROM Users where userName = ? AND password = ?');
// This sends the values separately, so SQL injection is a thing of the past
mysqli_stmt_bind_param($query, 'ss', $usr, $pw);
// Run the query
mysqli_stmt_execute($query);
// Prepared statements require to define exactly the fields you want
mysqli_stmt_bind_result($query, $user_id);
// Get the data
while(mysqli_stmt_fetch($query)){
echo $user_id;
}
mysqli_stmt_close($query);
Lastly, storing plaintext passwords is bad practice. Use a hashing library. PHP 5.5+ has one built-in (http://php.net/password). There's also a version for lesser PHP versions (https://github.com/ircmaxell/password_compat).
P.S. As pointed out in the comments (here's a link), your session_start() is in the wrong spot. That sends a header, so it requires that there be nothing echoed out before it.
<?php session_start(); ?>
<!DOCTYPE html>
<html>
Make sure that there is no whitespace (or anything) before the session_start().
Your problem is here:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
This should instead be
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
You're then passing the query string rather than a resource to mysqli_query.
(Also, refer to Shankar Damodaran's answer regarding the scope issue: pass $DB_connection to the SignIn function).
As a side note, you shouldn't use posted data directly into the query. You're at risk of SQL injection. Look into sanitizing the data or, preferably, prepared statements.
First of all, you are running into scope issues here.
In this line...
$result = mysqli_query($DB_connection,$query);
The variable $DB_connection is not accessible inside your SignIn() and thus your query is getting failed. Also you are mixing mysql_* (deprecated) functions with mysqli_* functions.
This simple and small code snippet for the login might help you..
$con = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($con));
$username = $_POST['username'];
$password = $_POST['userpassword'];
$result = mysqli_query($con,"SELECT * FROM users WHERE user_name = '$username' and user_password='$password'");
$count=mysqli_num_rows($result); // get total number of rows fetched. needs only 1 row for successful login.
if($count==1){
//Login successful
}
else{
//Login unsuccessful
}
It will fetch a row if the entered username and password are matched.It will fetch only one row as the username and password will be unique. If the count of rows fetched is '1' you can have successful login.
For some reason my check login script is letting in guests.
I have not made the site live yet so its all good.
I check the database for the username and the password the user puts in the html form but for some reason if it don't even get a result it still sets the username to nil
if it gets the result it sets the username to the username but if it don't get any results it sets the username to nothing.
I have a if statement but still setting it.
$myusername = mysql_real_escape_string($_POST['myusername']);
$mypassword = mysql_real_escape_string($_POST['mypassword']);
$sql = "SELECT * FROM users WHERE username='$myusername'";
$result = mysql_query($sql) or die(mysql_error());
$battle_get = mysql_fetch_array($result);
if ($battle_get['password'] == $mypassword)
{
$_SESSION['username'] = $myusername ; // store session data
header('Location: http://mydomainname.net/new_rpg/dashboard.php');
} else {
echo "wrong password" ;
}
You don't check if the user account actually exists. You just blindly fetch a row from the result set, even if that result set has NO records in it. That means $battle_get will be an empty array (or a boolean false if the query failed). You then do a string comparison against the submitted password. If that password is also empty, you're doing if (empty == empty) and boom... the user's in.
What you SHOULD be doing is:
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = "SELECT ... FROM users WHERE (username = '$username') AND (password = '$password')";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($sql) != 1) {
die("Invalid username and/or password"); // don't tell the user which failed.
}
Checking how many rows were returned is critical - if no rows are returned, then the user doesn't exist or the password is wrong. If 1 row is returned, then it's a valid login. If more than 1 row is returned, you've got duplicate username/password pairs in the database and need to fix that right away.
And, having just seen your "md5 is hard" comment above: You're dead wrong. MD5 is trivially EASY.
When you create the user record, you can hash the password easily:
INSERT INTO users (password) VALUES (MD5('$password'));
and for the login check:
SELECT ... WHERE (password = MD5('$password'));
Nothing to it at all.
Yur mistake:
Say I am not a user.
So $battle_get['password'] = false;
and $mypassword is also false,
so $battle_get['password'] equals $mypassword
Two way you can resolve this.
First, chek the password with sql:
$sql = "SELECT * FROM users WHERE username='$myusername' AND password = '$mypassword'";
or
if(!$battle_get) {
echo "wrong password" ;
}
This question already has answers here:
How to check username and password matches the database values
(3 answers)
Closed 11 months ago.
I have a form which has a textbox with the name attribute username and another one with the name attribute password.
I also have a database with columns called user and pass. When my users signed up it added the username to the user column and password to the pass column.
How would I make a MySQL query to check if the form submitted the right username and password and then if it did have a branch to let me input the code for if it succeeded?
I really need some code, this bit isn't going well I know it should be something like SELECT * FROM table WHERE username == $username AND... but then I'm stuck because I have an MD5 password in the database and that first bit is probably wrong. Please help. :)
Thanks
//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);
if ($user&&$pass)
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
//while loop
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
else
die("incorrect username/password!");
}
else
echo "user does not exist!";
}
else
die("please enter a username and password!");
Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).
You can limit the whole search to one row by using Limit 0,1
SELECT COUNT(UserName)
FROM TableName
WHERE UserName = 'User' AND
Password = 'Pass'
LIMIT 0, 1
1.) Storage of database passwords
Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.
2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.
The query should then look like this:
select hashedPassword from users where username=?
Then compare the password to the input.
Further questions?