I'm using this code to login user and I want to update the value in column loggedin to yes in mysql database. I tried to update it before sending header but it doesn't get updated. Where should I put the code to update the column?
if (isset($_POST['login']))
{
$username = trim(mysqli_real_escape_string($con, $_POST['username']));
$password = trim(mysqli_real_escape_string($con, $_POST['password']));
$md5password = md5($password);
// check user and password match to the database
$query = mysqli_query($con, "SELECT * FROM `user` WHERE username='$username' AND password='$md5password'");
// check how much rows return
if (mysqli_num_rows($query) == 1)
{
// login the user
// get the id of the user
$fetch = mysqli_fetch_assoc($query);
// start the session and store user id in the session
session_start();
$_SESSION['id'] = $fetch['id'];
$_SESSION['username'] = $fetch['username'];
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE userid = 1;");
header("Location: message.php");
}
else
{
// show error message
echo "<div class='alert alert-danger'>Invalid username Or password.</div>";
}
}
You're not updating the correct userid. You're updating userid = 1 instead of the ID belonging to the user who logged in. It should be:
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE id = {$_SESSION['id']};");
You need to change this:
UPDATE user SET loggedin = 'yes' WHERE userid = 1;
To this:
mysqli_query($con, 'UPDATE user SET loggedin = 'yes' WHERE userid = 1');
Please don't use the md5() function hashing passwords, it isn't safe, use these functions instead:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
You also use this:
if (mysqli_num_rows($query) == 1)
To check if the username exists, I suggest changing it to this:
if (mysqli_num_rows($query))
It does the same but you need less code to do it.
Other than that, please also learn how to prepare your queries before inserting them, your current code is vulnerable to SQL injection, more about that can be found here:
How can I prevent SQL injection in PHP?
Related
Here is my login process, I want a same dashboard but data will be different for each user. But I am stuck with creating uid variables to get data for each login user.
if(isset($_POST['login_btn']))
{
$email_login=$_POST['email'];
$password_login=$_POST['password'];
$admin="admin";
$co_admin="co_admin";
$query = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$admin' ";
$query_run = mysqli_query($connection, $query);
$query_co = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$co_admin' ";
$query_run_co = mysqli_query($connection, $query_co);
if(mysqli_fetch_array($query_run))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $admin;
header('Location: index.php');
}
else if(mysqli_fetch_array($query_run_co))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $co_admin;
header('Location: company_view.php');
}
else
{
$_SESSION['status'] = 'Email ID / Password / User Type is Invalid';
header('Location: login.php');
}
}
Above source code is for separating Co-admin and Admin. Now Any Co-Admin login to the portal he should get his own details, I would like to know which function I have to call or how should I declare a uid variable to fetch data tables for each current logged in user. I found some other source codes but which is not related to me so i am confused with how I fix it with those code. Can anyone do it in my codes.
I think you are asking how to get data for the current user from mysql tables. Yes, the standard way of doing this is via a unique ID for each user that is pulled from the registered_users table, storing this in the session, and then referencing this in the other tables and filtering by this ID. I would not suggest storing anything else from this table in the session as the ID is likely to have a stronger guarantee of imutibility.
For example if you have a table of recently visited pages per user, you would get this via:
$query = 'SELECT * from recently_visited WHERE user_id = ?';
$stmt = mysqli_prepare($query);
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
You can check the mysqli documentation for how to then extract what you need from the executed statement. I've shown this example of a prepared statement so you can see how to avoid SQL injection as well.
You may want to look into using foreign keys to enforce this connection.
Basically I am having issues with hashing and getting the password verified, and I was hoping someone could help me out by proof reading some of the code.
Below is the registration (php code):
include '../includes/connection.php';
$userID = $_POST['userID'];
$userName = $_POST['userName'];
$Pass = $_POST['password'];
$encrypted_password = password_hash($Pass, PASSWORD_DEFAULT);
if(!empty($userName) && !empty($Pass) && !empty($userID)){
$records = "SELECT * FROM Admins WHERE ID='$userID' OR Username='$userName' OR Password='$encrypted_password'";
$results = mysqli_query($connect,$records);
if ($results->num_rows == 1){
$message = "You have already requested an account.";
echo "<script type='text/javascript'>alert('$message');</script>";
}else{
$query = "INSERT INTO Admins (`ID`,`Username`,`Password`,`AdminLevel`) VALUES ('$userID','$userName','$encrypted_password','0')";
$run = mysqli_query($connect,$query);
$message = "Your request has been submitted.";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
Below is the login (php code)
if(!empty($userName) && !empty($Pass)){
$sql = "SELECT * FROM Admins WHERE Username='$userName'";
$sqlr = mysqli_query($connect,$sql);
$sqlrow = $sqlr->fetch_assoc();
$dbPass = $sqlrow['Password'];
$hash = password_verify($Pass, $dbPass);
if ($hash == 0){
die("There was no password found matching what you have entered.");
}else{
$records = "SELECT * FROM Admins WHERE Username='$userName' AND Password='$hash'";
$results = mysqli_query($connect,$records);
if ($results->num_rows == 1){
$row = $results->fetch_assoc();
$_SESSION['user_id'] = $row['ID'];
$_SESSION['admin_level'] = $row['AdminLevel'];
$_SESSION['user_name'] = $row['Username'];
$easyName = $_SESSION['user_name'];
$recordsS = "UPDATE `Admins` SET Status='1' WHERE Username='$userName'";
$resultsS = mysqli_query($connect,$recordsS);
header("Location: index.php");
}else{
die("Sorry... you have entered incorrect login information.");
}
}
}
This is the database heading: https://gyazo.com/69380c5cd0df0259d31799b71f33ce47
When I test this on the website and I login with correct information, "Sorry... you have entered incorrect login information." is echoed.
If I login with false information, "There was no password found matching what you have entered." is echoed.
Why can it detect the password, but not properly execute the else statement in the login section?
Your $records query is failing because you are selecting Password='$hash'" where $hash is either true, or false. The query should have this condition: Password='$dbPass'"
Just as a gut check: The important thing to note is the password field in the database should be huge. The password_hash() can generate some very lengthy text (the current default is 60 characters), so making the field larger will allow for the length needed. Secondly the PHP team is adding more algorithms to the method which means the hash can and will grow. We also do not want to limit our user's ability to use the password or passphrase of their choice. It's best to leave room for the changes.
One more thing: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
You have a small mistake in the Query:
$records = "SELECT * FROM Admins WHERE Username='$userName' AND Password='$hash'";
You are matching password against a boolean by mistake. It should be:
$records = "SELECT * FROM Admins WHERE Username='$userName' AND Password='$dbPass'";
You need to hash the $Pass variable for this match. The function password_verify returns a boolean after making the match but the actual hash is done inside the method.
This is a login script I am working on; It uses mysqli (I know it is not as secure as PDO)
After running the MySQL query I am fetch_object(). I am then assinging $_session to hold the user ID and email. $_SESSION['uid'] = $user->ID works but not $_SESSION['uemail'] = $user->email. Could this be because of email is stored in the object $user? Do I have to convert it somehow?
email is store ass a varchar(255) in the database ID is a int(11).
<?php
include_once("config.php");
$username = $_POST['username'];
$password = sha1($_POST['password']);
$query = "SELECT ID FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";
if ($result = $db->query($query)) {
while ($user = $result->fetch_object()) {
$_SESSION['uid'] = $user->ID;
$_SESSION['uemail'] = $user->email ;
header("Location: index.php");
//exit();
}
}else {
echo "Invalid login information. Please return to the previous page.";
//exit();
}
//var_dump(get_object_vars($result));
//$db->close();
?>
Thanks in advance.
Comment to answer:
You need to select the column(s) for which you are querying for:
SELECT ID, email FROM ...
which is why $_SESSION['uemail'] = $user->email ; is failing.
Either choose the specific column(s) in question, or a SELECT * would also work.
However and it's been said before, that using * isn't suggested, therefore select the actual column(s).
you are not selecting the email column from the database.
Try:
$query = "SELECT ID, email FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";
I'm new to mysql and php.
Been working on creating a database with a table for users.
I've managed to successfully add users to the database, and their passwords with md5(yea i know it's not secure), it's not going to be launched online.
My problem is, how do I log a user in, based on their correct username and password.
here is my code
My logic is taht after the query runs, it will return either true or false.
If true, then display successful login, else unsuccessful.
however, even if i input a correct username and password, i still get a unsuccessful login message
i checked the mysql database, and the uesrname is in there correctly
ideas?
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result == true) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
I'm not entirely sure your SQL will run, but just to be on the safe side.
Change it so that
$password_hash = md5($password);
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = '$password_hash'";
And for your original question
if(mysql_num_rows($result) == 1) { //If the SQL returns one row, that means that a user was found with `userName = $username` and `password = md5($password)`
// Login
} else {
// Authentication Failed
}
Also, consider using MySQLi instead of MySQL since it has been depreciated.
First of all, protect your code against SQL injections.
Then, make sure that the password in the DB is really hashed with md5() function.
Make sure you form uses POST method to pass the data to the script.
Try the following code:
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '". addslashes($username) ."' AND password = '". md5('$password')."'";
$result = mysql_query($sql);
if (mysql_num_rows($result)>0) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
mysql_query doesn't return TRUE or FALSE. Per the docs (http://php.net/manual/en/function.mysql-query.php), it returns a resource if successful, or FALSE if there is an error. You need to evaluate the resource to see if it's valid.
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result && $row = mysql_fetch_assoc($result)) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
As mentioned in my comment, the issue seems to be your sql string. Instead of hashing, you are putting the method into the string. So change
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
to
$sql = "SELECT * FROM `users` WHERE userName ='$username' AND password = '".md5('$password')."'";
Your result will not be true or false, but since php treats any value not a 0 as true, it will work as is.
Also, it is strongly recommended to escape all data going into your sql string to prevent sql injection. Another note: mysql is being deprecated, so now would be a great time to move to something like mysqli.
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" ;
}