Fetching data from mySql database for php user session - php

I'm relatively new to PHP and mySQL, and I'm trying to create user sessions with fields from a mySQL database.
The way I've set it up means that I am getting a session with the two fields entered into the login form (username and password) by checking these against the database, but I cannot retrieve any other data from the database and add it to the session.
How can I retrieve other data from the database and add this to the new session?
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
//This one works
$_SESSION['username'] = $username;
//This one doesn't
$_SESSION['email'] = $rows ['email'];
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<p>Username/password is incorrect.</p>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
}
?>

$rows is counter variable (having count of number of records) there that's why not working.
Do like below:-
....previous code as it is
$result = mysqli_query($con,$query) or die(mysql_error());
$row = mysqli_fetch_assoc($result); //fetch record
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $row['email'];
header("Location: index.php");
}...rest code as it is
Note:-
1.Don't use md5 password encryption, use password hashing technique.
2.Use prepared statements of mysqli_* to prevent your code from SQL Injection

Related

How to match a inputted password to hashed password from database?

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

how to store session value in another table?

I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement

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.

pull userId from DB with email and store user ID in session

So here is my code for the login page for my site, I want it to pull the user ID from the DB when the user logs in and store it in the session data. WHich I will be using in another page to pull a value from a different table.
<?php
session_start();
//Connect to DB
include_once 'db_connect.php';
// escape variables for security
$Email = mysqli_real_escape_string($mysqli, $_POST['email']);
$Password = mysqli_real_escape_string($mysqli, $_POST['password']);
//password hashing
$Password = hash("sha256", $Password);
$sqli="SELECT * FROM users WHERE Email='$Email' and Password='$Password'";
$result=mysqli_query($mysqli, $sqli);
//Mysql_num_row is counting table row
$count=mysqli_num_rows($result);
// If result matched $Email and $Password, table row must be 1 row
if($count==1){
//redirect to file "menu.html"
header("location:menu.html");
}
//If all else fails they shall not pass!
else {
echo "Wrong Email or Password. YOU SHALL NOT PASS!";
}
?>
To get the ID from the table on your database use mysqli_fetch_array or mysqli_fetch_assoc
Insert this below your $result
while($row = mysqli_fetch_array($result)): //fetching the row from database
$id = $row['id']; //the id column in your table
$_SESSION['id'] = $id; //the id is now saved in your session for future use
endwhile;
In another page don't forget to session_start(); to access $_SESSION['id'] so that you can access different information associated with that id from the table in your database.
Ok, so what you need to do is fetch the user id from the database. Presuming the users table has a column called id:
$result=mysqli_query($mysqli, $sqli);
//Mysql_num_row is counting table row
$count=mysqli_num_rows($result);
// If result matched $Email and $Password, table row must be 1 row
if($count==1){
$row = mysql_fetch_array($result);
$_SESSION['userID']=$row['id'];
header("location:menu.html");
die();
}
Note that mysql_fetch_array is usually called within a while loop, to get multiple rows. However here you only have one row, so that is not needed
if ($count == 1) {
//redirect to file "menu.html"
While ($row = mysql_fetch_array($result)) {
$userName = $row['username']; // Where username is the user ID value in your db
$_SESSION['username'] = $userName;
header("location:menu.html");
}
}

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