I am pretty new to PHP, so debugging isn't really something I am familiar with when it comes to PHP.
I am using php/javascript(ajax) to change a users password for my website.
So basically, when I log in and try to change my password. The code breaks at the first echo. So the password that I am entering into the form does not match the password in the database. But, I am using the same hash method and everything. If anyone has any ideas, let me know. Thanks!
if(isset($_POST["u"])) {
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$oldpasshash = md5($_POST["cp"]);
$newpasshash = md5($_POST["cnp"]);
$sql = "SELECT id, username, password FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row["id"];
$db_username = $row["username"];
$db_password = $row["password"];
if($db_password != $oldpasshash){
echo "no_exist";
exit();
} else {
$sql = "UPDATE users SET password='$newpasshash', WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
$sql = "SELECT id, username, password FROM users WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_newpass = $row[3];
if($db_newpass == $newpasshash) {
echo "success";
exit();
} else {
echo "pass_failed";
exit();
}
}
Look at your first two lines of code:
if(isset($_POST["u"])) {
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
You check if $_POST['u'] isset then you use $_GET['u'].
FYI, you are injecting $u directly into the mysql statement, don't do this.
You are using mysqli_fetch_row and accessing the table fields via field name. That is wrong.
mysqli_fetch_row fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero).
So you have to use
$db_id = $row[0];
$db_username = $row[1];
$db_password = $row[2];
Related
This question already has an answer here:
I cannot get my login form to connect interact properly with mySQL database [closed]
(1 answer)
Closed 6 years ago.
I am very new to php and I am trying to create a login system. Here is my code
<?php
$con=mysqli_connect("XXXXXXX","XXXXXXXX","XXXXXXXXX","XXXXXXXXXX");
if (!$con)
{
echo "failed to connect";
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT userID FROM users WHERE username = $username and password = $password;";
if (!$sql) {
echo 'query invalid'.mysql_error();
}
$result = mysql_query($sql);
echo "$result";
$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
mysql_close($con);
?>
I am sure there is no problem with the connection. But my result is not showing up and there is no error message. Previously I had an IF statement that perform further action if the result comes back. Since I am trying to figure out what is going on, I just deleted that part. Somebody please help. Many thanks
You're missing the single quotes around the variables, and also you're using mysql mixed with mysqli, which will not work.
$sql = "SELECT userID FROM users WHERE username = '$username' and password = '$password';";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($sql); // same as fetch_array with MYSQLI_ASSOC
$active = $row['active'];
$count = mysqli_num_rows($result);
You don't need mysql_close at the end, but if you want to use it, it's mysqli_close($con);
Keep in mind this is unsafe.
Use this function to filter user input:
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
Read this to make sure your code follows the security standards.
I recommend this.
$sql = "SELECT userID FROM users
WHERE username = " ._sql($username) ." and password = " ._sql($password);
// generate sql safe string function
function _sql($txt) {
if ($txt === null || $txt === "")
return "NULL";
if (substr($txt, 0, 2) == "##")
return substr($txt, 2);
//$txt = str_replace("'", "''", $txt);
$txt = mysql_real_escape_string($txt);
return "'" . $txt . "'";
}
When a user signs in i want to echo back there ID (which is created because of the auto_increment in phpMyAdmin) from there account, here's my login.PHP:
<?php
$conn = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$Email = $_POST["Email"];
$Password = $_POST["Password"];
$sql_query = "select Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
echo "Welcome: Buyer";
}else{
$int = 1;
//echo "Buyer login failed...";
}
}else{
echo "Login failed...";
}
}
mysqli_stmt_close($statement);
mysqli_close($conn);
?>
Add the column name id in your sql query.let say your column name for id is ID
$sql_query = "select ID,Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
$user_id = $row['ID'];
echo $user_id;
echo "Welcome: Buyer";
}
Since your making login in php its good choice to use $_SESSION.
All you need to do is add a session_start(); at the top of any php script where you need to use session.
<?php
session_start();
$conn = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$Email = $_POST["Email"];
$Password = $_POST["Password"];
$sql_query = "select ID,Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
$user_id = $row['ID'];
//using session
$_SESSION["user_id"] = $user_id;
echo $user_id;
echo "Welcome: Buyer";
}
Now you can access anywhere in your php script using the $_SESSION variable.
echo $_SESSION["user_id"] ;
Let's start from the beginning. You create a login form, you store sessions based on the values:
login.php
session_start();
$_SESSION["username"] = $username;
main.page
$username = $_SESSION["username"];
echo "Hi $username";
EDIT 2
Ok, so you want to check if username exists and then echo their ID. Regardless, almost all login systems have sessions.
After logging in, let's say you have a $_SESSION of id.
php
session_start();
$id = $_SESSION["id"];
$db = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$check = $db->query("SELECT * FROM users WHERE id='$id'");
$num_check = $check->num_rows;
$fetch_check = $check->fetch_object();
$id2 = $fetch_check->id;
if($num_check) {
// User Exists
echo $id2;
} else {
echo "You don't exist."
}
Please note, normally, I would just echo $id. However, the OP requested to echo the id from the db, so I echoed $id2.
How can retrive data.here login not working.I used mysqli_fetch_array,but before while the condition failed.
<?php
session_start();
include 'db.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM tbl-login where username='".$username."'");
$n = 0;
while($row = mysqli_fetch_array($query)) {
// $u-id = $row['u-id'];
$dbusername = $row['username'];
$dbpassword = $row['password'];
$usertype = $row['usertype'];
$_SESSION['usname'] = $dbusername;
$_SESSION['uid'] = $u-id;
$_SESSION['usertype'] = $usertype;
if ($dbusername == $username && $dbpassword == $password) {
$n++;
echo "grtet";
// header('location:dashboard.php');
}
}
if ($n == 0) {
header('location:index.php');
}
?>
$query = mysqli_query($connect,"SELECT * FROM tbl-login where username='".$username."' and password='".$password."'");
$row = mysqli_fetch_row($query); // Just ONE row, because expecting is, there is only one user with this USERNAME
if(empty($row)) {
echo 'Invalid username or password';
}else{
echo 'OK :)';
}
When you're not sure what makes a query fail, call mysqli_error(). While I haven't tested myself, I believe tbl-login is the cause of the error (which mysqli_error() should return if you call it).
MySQL allows spaces and non-identifier characters to be table/column name, but when referring to such a name, you need to enclose it between backtick (`). Hence tbl-login should be written as `tbl-login` in the SQL query.
You Have Created table name as tbl-login, column name as u-id and variable as $u-id, which i think is a problem. If Possible, change your column name, table name and variable name. Here are some links to get basic idea for creating variable name, column name, table name.
Create Variables, Create Table, Identifiers
I've updated your code. Please have a look.
<?php
session_start();
include 'db.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM `tbl_login` WHERE username='$username' AND password='$password'");
$rowcount = mysqli_num_rows($query);
if($rowcount > 0) {
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$_SESSION['usname'] = $row['username'];
$_SESSION['uid'] = $row['u_id'];
$_SESSION['usertype'] = $row['usertype'];
header('location:dashboard.php');
}
} else {
header('location:index.php');
}
?>
I send a password to php to get compared to the hash stored in the database.
my php is:
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
$query = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$passHash = mysql_result($query, 0);
if(password_verify($enteredPass, $passHash)){
echo "success";
}else{
echo "failure";
}
I also tried using mysqli_fetch_array() as well, but it still doesn't work. Does anyone know why this isn't working? thanks in advance to anyone who can help. (on a side note, $passHash returns null)
You are mixing two extensions, mysqli and mysql - mysqli_query and then mysql_result.
You are also open to SQL injection and should be sanitising your POST input before passing it directly to MySQL.
mysqli_query returns a result object and you then need to fetch the results from that object.
mysqli_fetch_row will return one row.
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
//...
$resultset = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$result = mysqli_fetch_row($resultset);
if(password_verify($enteredPass,$result[0])){
echo "success";
}else{
echo "failure";
}
I did solve my own problem with a simple while loop, i guess it will work fine, thanks everyone for your input:
$passHash = '';
while ($row = mysqli_fetch_array($query)) {
$passHash .= $row["passhash"];
}
Give this a try:
$enteredUser = mysqli_real_escape_string($con,$_POST["username"]);
$enteredPass = mysqli_real_escape_string($con,$_POST["password"]);
$sql = "SELECT * FROM `user` WHERE `username` = '$enteredUser'";
$result = $con->query($sql);
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($enteredPass, $row['passhash']))
{
echo "Success";
}
else {
echo "Sorry";
}
This is my code
$username = $_POST['user'];
$password = $_POST['pass'];
if (isset($_POST['user'])); {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")){
while($row = mysqli_fetch_assoc($query)){
$row['pass'] = $setpassword;
}
mysqli_free_result($query);
}
}
What it currently does is from a form, retrive a username and password that the user has entered, take that username and find the row with that username and get the password from that row and set it as the variable $setpassword. Below is the code to check if the password matches the given username on the database.
if ($password=='') {
$verify = 0;
}
if ($password!='') {
if ($password!=$setpassword) {
$verify = 1;
}
if ($password==$setpassword) {
$verify = 2;
}
}
If verify is...
0 - The Login Form Will appear as nothing has been entered.
1 - Incorrect Password will be displayed along with the login form.
2 - Correct Password will be displayed and the username will be assigned to a session variable.
I'm having a problem where a user can enter a username that doesnt exist and any password wether its in the database or not and it will be verified.
What can I do to check if the username doesn't exist on the database?
When you are accepting the user's registration query the database to see if it already exists.
$result = mysqli_query("SELECT * FROM accounts where `user` = $username");
if(mysql_num_rows($result) >0) // if there are any rows returned then the username exists
{
//User Name already exists
}
else
{
//User name doesn't exist, add user
}
I'm not sure this is where you are doing that. But to eliminate duplicates you can do it that way. Also, you can define the column user as unique. That way the SQL will not allow duplicate values.
Also this line:
$row['pass'] = $setpassword; //setting $row['pass'] to $setpasswords value.
This is reversed. You should be doing it the other way around.
$setpassword = $row['pass']; //setting setpassword to $row['pass'] value.
Let me know if I need to clarify anything.
Try this:
$username = isset($_POST['user'])?$_POST['user']:''; // check if isset to avoid notice
$password = isset($_POST['pass'])?$_POST['pass']:'';
$verify = 0;
if (!empty($username)) {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")) {
while($row = mysqli_fetch_assoc($query)){
$setpassword = $row['pass'];
break; // exit the loop once you found the password
}
mysqli_free_result($query);
}
if (isset($setpassword)) {
$verify = 1;
if ($password == $setpassword) {
$verify = 2;
}
}
if (isset($_POST['user'])); {
there is an extra semicolon in this line, making whole code not working
to do your verification, all you need is to retrieve the password and compare it with entred one:
$row = mysqli_fetch_assoc($query));
if ($row AND $row['pass'] == $password)
$verify = 1;
}
note that $row could be ampty, so, you have to check it first
however, you can do both comparisons in the query, like this
"SELECT * FROM accounts where `user` = $username" AND `pass` = '$password';
However, your code suffers from 2 common problems.
It is better to save a hash instead of the plain password.
You should sanitize your data before adding it in the query
at least this way:
$username = mysqli_real_escape_string($db,$_POST['user']);