Can't receive mysqli record with password verify - php

I just started working with php and I'm not really good at it.I need to verify my user's password and username after they passed that I want to start an session with that users user_id. But everytime I try to echo the user_id I just get nothing back. hope someone can help me with this. is my code:
<?php
require_once "config.php";
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
if (strlen($username) > 0 && strlen($hash) > 0){
$query = "SELECT user_id FROM keep_user WHERE username = '$username' AND password = '$hash'";
$result = mysqli_query($conn , $query);
if($conn->query($query) == TRUE){
if(password_verify($password, $hash)){
session_start();
$_SESSION['user_id'] = $user_id;
echo $user_id;
echo "succes";
}else{
echo "error-1".$conn->error;
}
}else{
echo "error-2".$conn->error;
exit;
}
}else{
echo "error".$conn->error;
exit;
}
?>
It does echo success so I am guessing that part is good but why can't retrieve user_id?

Problem is not with password_verify function . Problem is with mysqli_query because you execute your query two times
$result = mysqli_query($conn , $query);// first time
if($conn->query($query) == TRUE){// second time
Just comment or remove $result = mysqli_query($conn , $query);// first time
To get user id form query you need to fetch it as
if ($result = $conn->query($query)) {
/* fetch associative array */
$row = $result->fetch_assoc() ;
$user_id=$row["user_id"];
$_SESSION['user_id'] = $user_id;
}
And session_start(); at the top of your page.
You script is open for sql injection Read How can I prevent SQL injection in PHP? to prevent it

Related

How to make a new session with customer id? PHP/Mysqli

I have a login page which generates $_SESSION['username'] = $username.
I want to create new session $_SESSION['id'] which stores customer's id not username and pass it to another page.
I'm still learning so please make your answer understandable. Thanks
here's my login code
<?php
require('dbConfig.php');
session_start();
if(!empty($_SESSION["username"])){
header("LOCATION:index.php");
}
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($db,$username); //escapes special
characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($db,$password);
$query = "SELECT * FROM `members` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($db,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
header("Location: index.php");
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
Make sure session_start() is present is every page and add this in the session creation section of your code:
$_SESSION['id'] = $result['id'];
under
$_SESSION['username'] = $username;
I am asuming your "id" is called "id" in your table
You can use
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
To check whats in your session
First of all: try to use mysqli_prepare to query user, by passing variable directly into SQL code, you open your system to SQL Injection.
$query = "SELECT * FROM `members` WHERE username=? and password=?"
$password = md5($password);
$statement = mysqli_prepare($db, $query);
mysqli_stmt_bind_param($statement, 'ss', $username, $password); //bind variables before execute sql command to prevent SQL injection.
mysqli_stmt_execute($statement);
$result = mysqli_stmt_get_result($statement);
$rows = mysqli_stmt_affected_rows($statement);
if($rows==1){
$user = mysqli_fetch_array($result, MYSQLI_ASSOC)
$_SESSION['username'] = $username;
$_SESSION['id'] = $user['id'];
header("Location: index.php");
}
Also, you must include session_start(); inside index.php in order to read SESSION variable on index.php page.

How to fetch username and matched id as Session?

I am trying to fetch different stats from whatever user is logged in. Then echo these stats out. currently when logging in i am setting a session with the username. Then i am trying to fetch the id from this username and check it again the table with the same ID and then fetch the rows from that table.
My guess is that since i am starting a session with only the username on login the code to fetch data wont work since the session does not provide the id row. i am unsure of how to get it to do that or if i am even right about that.
I appreciate all help, i am really stuck here.
This is my login code:
$query = "SELECT password FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
//USERDATA
$dbPassword = $row['password'];
if (password_verify($password, $dbPassword))
{
// echo "The details are correct.";
$_SESSION['loggedin'] = $username;
require_once('../../frontend/templates/account-actions.php');
}
else
{
echo "Passwords do not match!";
}
This is my code to fetch the stats data from the id of the username logged in:
$id = $_SESSION['loggedin'];
$query = "SELECT * FROM stats WHERE id='$id'";
$stmt = mysqli_query($conn, $query);
$result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);
I have converted your code to mysqli Prepared Statement with Procedural approach.
$username = "username_to_search";
$password = "password"; //Password is in plain text since password hash has been used.
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE username = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $username); //"s" defines the type of data in the following variables, i.e. String for $username.
/* execute query */
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$total_rows = mysqli_stmt_num_rows($stmt);
mysqli_stmt_bind_result($stmt, $id_fetched, $username_fetched, $password_fetched); //store every field fetched from the table in sequence. Note that I have added _fetched to make it easier to identify later.
if ($total_rows > 0) {
while(mysqli_stmt_fetch($stmt)) {
if (password_verify($password, $password_fetched)) {
$_SESSION['user_id'] = $id_fetched;
$_SESSION['username'] = $username_fetched;
require_once('../../frontend/templates/account-actions.php');
}
else {
echo "Invalid Password!";
}
}
} else {
echo "Invalid Username!";
}
Once you have stored the SESSION variables properly, now you can easily find everything related to this. User your $_SESSION["user_id"] to search.

How can I bypass my login script?

I've created a below script, which is intentionally not secure, in order to learn a bit more about cyber security.
session_start();
if($_SESSION['userSession']) {
header("location: home.php");
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
$con = mysqli_connect("localhost", "myUsername", "myPassword", "myDatabase");
if(!$con) {
die("Error: " . mysqli_connect_error());
}
$query = "SELECT * FROM users WHERE username = '$username' && password='$password'";
$result = mysqli_query($con, $query);
$numResults = mysqli_num_rows($result);
if($numResults == 1) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['userSession'] = $row['id'];
header("location: home.php");
} else {
echo "Error Logging In";
}
mysqli_close($con);
}
As you can see, I have not escaped the user input and the password has not been hashed.
Therefore, I am presuming that this should be an easily hackable login. However, I have attempted to use the below input in both of the username and password fields, but always get the output "Error Logging In".
password' OR '1' = '1'";
How can I try to bypass/hack my login script?
If we use sql statement directly to fetch username and password field then it can be bypass with ' OR '1' = '1 pattern, because when you put ' OR '1' = '1 in username and password field that values carry forward to sql statement and in that statement ' or '1' = '1 is true for all the cases and that's a reason login can bypass.

Getting hashed password with prepared statements

I can't get this to work. I am new to working with prepared statements so i i'm kinda 50/50 on what i'm doing.
Upon registration, the password is hashed with password_hash($pass,PASSWORD_DEFAULT)
Now, i'm trying to get my login page to function with this but i dont know where / how to write it with the password_verify()
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE BINARY username=? AND password=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if($num_rows == 1){
$rows = $result->fetch_assoc();
if(password_verify($password, $rows['password'])){
$_SESSION['loggedin'] = $username;
$_SESSION['country'] = $rows['country'];
$_SESSION['email'] = $rows['email'];
$_SESSION['avatar'] = $rows['u_avatar'];
$_SESSION['is_gm'] = $rows['is_gm'];
$_SESSION['user_lvl'] = $rows['user_lvl'];
$_SESSION['totalposts'] = $rows['post_total'];
$_SESSION['totalcoins'] = $rows['coins_total'];
$_SESSION['totalvotes'] = $rows['vote_total'];
$_SESSION['secquest'] = $rows['sec_quest'];
$_SESSION['secanswer'] = $rows['sec_answer'];
$_SESSION['join_date'] = $rows['join_date'];
header("Location: /index.php");
exit();
}
} else {
echo "<p class='error_msg'>No accounts could be found with the given credentials.</p>";
}
$stmt->free_result();
$stmt->close();
$db->close();
I would assume that the password verify would before if($num_rows == 1) but as i said, i have no idea.
Your query is essentially:
SELECT * FROM users WHERE username=username AND password_hash=plain_text_password
This isn't going to work. If you're relying on PHP password hashing, you can't do a password comparison on the SQL level. Retrieve the password hash from the database then do the password_verify (exclude the password=?) in your WHERE arguments.

mySQL statement not working inside of php

Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version
Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}
I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.

Categories