assign $_session var from object - php

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";

Related

Mysql Query not returning my results when adding variables into the query [duplicate]

This question already exists:
How to construct an SQL query correctly in a PHP script? [duplicate]
Closed 5 years ago.
If I run this with the query
"SELECT * FROM users";
It returns my result. But as soon as I run this
$username = $_POST['username'];
$password = $_POST['password'];
$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";
it doesn't.
If I run it in Mysql workbench without the variables it works. If I run echo the $_POST values they come through correctly.
I am stumped as to what I'm doing wrong PLEASE!! help me.
I also ran my code through https://phpcodechecker.com/ and it cant see any errors in my code.
This is the full function.
function login($username,$password){
global $db_conn;
$conn = new mysqli($db_conn['servername'], $db_conn['username'], $db_conn['password'], $db_conn['dbname']);
$username = $_POST['username'];
$password = $_POST['password'];
$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";
$login_result = $conn->query($login);
if ($login_result->num_rows > 0) {
$output = array();
while($row = $login_result->fetch_assoc()) {
$output[] = $row;
echo "".$row['name']."-".$row['password']."<br>";
}
} else {
echo "Invaild Login Details!"."<br>" ;
$conn->close();
return false;
}
}
Every time it says "Invalid Login Details!" But I know their is one result that gets returned.
What am I doing wrong?
Inserting variables into your SQL directly is a major source of SQL Injection Attacks. Use PDO for security.
https://www.php.net/manual/en/book.pdo.php#114974
change the query like this
$login = "SELECT * FROM users WHERE name= '$username' AND password= '$password'";
note: this method is prone to sql injection attacks. try prepared statements to avoid it
try with ''(single quote) for comparing name and password
"SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";
$login = "SELECT * FROM users WHERE name = '{$username}' AND password =
'{$password}' ";
You can simply specify the variables no need to go for string append to construct query in php
Eg :
Query = "SELECT * FROM `users` where username = '$username' AND password = '$password' " ;
try following code
$login = "SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";

Why is this login and registration system not checking the password correctly?

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.

update column in mysql database when user logs in

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?

user login with php and mysql database

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.

mysql - fetching data from table row

I have gotten a snippet of code to bring back the username and password and see if they match. i now want to set a session varaible to the 'points' value i have in the table which is in the same row as the username and pass.. what could be done?
<?php $username="asdin";
$password="1sdA2";
$database="a75sdting";
$pword = $_REQUEST['pword'];
$uname = $_REQUEST['uname'];
mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
$exsists = 0;
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
break;
}
if ($exsists){
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}
mysql_close();
?>
i want to set $_SESSION['points'] = $row[points] i guess... but i dont think that is correct
<?php
// start session (required on every page that uses sessions
session_start();
// db auth
$username="asdin";
$password="1sdA2";
$database="a75sdting";
// user auth
$pword = $_POST['pword']; // should use either $_POST or $_GET, NOT $_REQUEST
$uname = $_POST['uname']; // should use either $_POST or $_GET, NOT $_REQUEST
// open db connection
$conn = mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database,$conn) or die( "Unable to select database");
// check user
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
if(mysql_num_rows($query)){
// user exists
$row = mysql_fetch_assoc($query);
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}else{
header('Location: http://wwsdipts/login.php'); // take them back to login page if incorrect details
}
// close db connection
mysql_close($conn);
?>
I've tidied up your code a bit, please take a look at the notes. It is also worth nothing the following:
You should be using some sort of protection against SQL injections, such as mysql_real_escape_string($_POST['uname']) - the same for password
You need session_start() on all pages that use session variables
You shouldn't use $_REQUEST, use either $_POST or $_GET (read about it)
Do you actually have a table named username? You should read up a bit about DB design, a better name/use for this table would be users as the table will be holding users (a combination of unique ID, username & password.
I don't know what you mean about points, but to access any column name in the "username" table, use $row['column-name'] after it is set ($row = mysql_fetch_assoc($query);)
If you intend on using PHP a lot in the future, you should look up PDO, it's a great class for handling SQL.
you are right, but in this case your array is rows, and it should be in
$_SESSION['points'] = $rows['points']
And it should be in your while loop:
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
$_SESSION['points'] = $rows['points']
break;
}
However, it might be better to do something like this:
if(mysql_num_rows($result) == 1) {
//Login Successful
rows = mysql_fetch_assoc($result);
$_SESSION['points'] = $rows['points']
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}

Categories