Reset password confirmation does not work properly? - php

It works if i put it like that where user_id = 3 or when i remove the where statement(WHERE user_id=".$user['user_id'].") but then all my password in the db change.
I used get method to get the userid like that
user_id=3&reset_token=xxxxxxxxx
<?php
if( isset($_GET['user_id']) && isset($_GET['reset_token']) ) {
$userid = $_GET['user_id'];
$reset_token = $_GET['reset_token'];
// Make sure user email with matching hash exist
$req = $heidisql->prepare("SELECT * FROM users WHERE user_id='$userid' AND reset_token='$reset_token' ");
$req->execute($userid, $reset_token );
$user = $req->fetch(PDO::FETCH_ASSOC);
if ($user) {
if (!preg_match ('%\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{8,30}\z%', $_POST['new_pass'])
|| $_POST['new_pass'] !== $_POST['confirm_newpass'] ) {
echo 'Your new password did not match the new confirm password or is invalid!';
exit();
}
}
} else {
$newpassword = escape_data($_POST['new_pass']);
$newpass_hash = password_hash($newpassword, PASSWORD_BCRYPT);
$sql= "UPDATE users SET "
. "password_hashcode='$newpass_hash', "
. "reset_allocated_time=NULL, "
. "reset_token=NULL "
. "WHERE user_id=".$user['user_id']." "; //<- error here
// Make sure user email with matching hash exist
$result_newpass = $heidisql->prepare($sql);
$result_newpass->execute();
echo "Your password has been reset!";
exit();
}
already try user_id = '$userid'/ $_GET['user_id']
So, how should i define the variable user_id?
Still does not work
$req = $heidisql->prepare("SELECT * FROM users WHERE user_id=':user_id' AND reset_token=':reset_token' ");
$req->execute([':user_id'=>$userid, ':reset_token'=>$reset_token]);
$sql= "UPDATE users SET password_hashcode=':password_hashcode', reset_allocated_time=NULL, reset_token=NULL WHERE user_id=:user_id";
$result_newpass = $heidisql->prepare($sql); $result_newpass->execute([':user_id'=>$userid,':password_hashcode'=>$newpass_hash, ':reset_token'=>NULL, ':reset_allocated_time'=>NULL]);
- I believe the problem may lies with the get method cause it seems that I cannot properly access the user_id/reset_token in the URL?
...localhost/example/reset_pass.php?user_id=xx&reset_token=xxxxxxxxx
I am getting undefined variable at user_id
Anyone knows if that the problem(s) cause my password validation also does not work?

Update this $sql from here:
$sql = "UPDATE users SET
password_hashcode = '$newpass_hash',
reset_allocated_time = NULL,
reset_token = NULL
WHERE user_id = '$user['user_id']'";

When using prepared statements you don't actually include the values in the statement. Instead you use placeholders, and bind the values later.
Change:
$req = $heidisql->prepare(
"SELECT * FROM users WHERE user_id='$userid'
AND reset_token='$reset_token' "
);
$req->execute($userid, $reset_token );
To:
$req = $heidisql->prepare(
"SELECT * FROM users WHERE user_id=:id
AND reset_token=:token "
);
$req->execute([':id'=>$userid, ':token'=>$reset_token]);
See the docs
Further down, you have:
$newpassword = escape_data($_POST['new_pass']);
$newpass_hash = password_hash($newpassword, PASSWORD_BCRYPT);
It's probably a bad idea to change the password (escape) before hashing it. Just hash it; the result will be safe to use. Changing it runs the risk of the user's true password not being recognized if your escape function changes in the future.
Further down you should change:
$sql= "UPDATE users SET password_hashcode='$newpass_hash',"
. "reset_allocated_time=NULL, reset_token=NULL "
. "WHERE user_id=".$user['user_id']." "; //<- error here
$result_newpass = $heidisql->prepare($sql);
$result_newpass->execute();
To:
$sql= "UPDATE users SET password_hashcode=:newpass,"
. "reset_allocated_time=NULL, reset_token=NULL "
. "WHERE user_id=:id"; //<- error here
$result_newpass = $heidisql->prepare($sql);
$result_newpass->execute([':newpass'=>$newpass_hash, ':id'=>$userid]);

Related

PHP Server-Side Validation of Related Fields

I have a user table with userid and password. I would like all form submissions to be 'verified' by another user by entering userid and password before submission. I have a code that works to verify the userid, but I would like to also verify the password, but obviously linked to the userid. This is NOT a login form, all it does is verify that a users entered userid and password are correct.
The 'verify' fields in my form are called: userid_ver and password_ver.
Any help is very appreciated! Thank you.
$rs = CustomQuery("select userid from user where userid = '"
. db_addslashes($values["userid_ver"]) . "'");
if (db_fetch_array($rs)==false)
{
$message = "UserID is incorrect. Please try again.";
return false;
}
$message="";
return true;
I think you made a mistake should be userid_ver = '...
Anyway if you are asking just to add a checking in your query, then add this at the end of your sql statement, just be sure that the $values["password_ver"] is set:
." AND password_ver = '". db_addslashes($values["password_ver"]) . "'"
Complete:
$rs = CustomQuery("select userid from user where userid = '"
. db_addslashes($values["userid_ver"]) . "' AND password_ver = '". db_addslashes($values["password_ver"]) . "'");
if (db_fetch_array($rs)==false)
{
$message = "UserID is incorrect. Please try again.";
return false;
}
$message="";
return true;

PHP/MySQL log in system -

I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.

how to update data in mysql without update image first

I want to update my data in mysql.
But, if i want update (ex. firstname), photo_profile will lost.
<?php
include 'function_page_user.php';
if(($_FILES['photo_profile']) and ($_POST['firstname']) and ($_POST['lastname']) and ($_POST['password']))
{
session_start();
include 'connect.php';
$foldername="assets/img/user/";
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$pwd = mysql_real_escape_string($_POST["password"]);
if((!empty($firstname) and !empty($lastname) and !empty($pwd)) and($_FILES['photo_profile']))
{
$image = $foldername . basename ($_FILES['photo_profile'] ['name']);
mysql_query ("update user set firstname = '".$firstname."' , lastname = '".$lastname."' , password = '".$pwd."' , photo_profile='".$image."' where id_user ='".$_SESSION['id']."'");
move_uploaded_file($_FILES['photo_profile']['tmp_name'], $image);
echo "<script>alert ('File Succes To edit');</script>";
$page="formubahuser.php";
echo redirectPage($page);
}
else echo "variabel empty";
}
else
echo ("your data is not complete<a href=formubahuser.php>Fill it again</a>");
?>
You have a number of major problems in your code. Before you continue, you need to read about the following topics:
1) The php mysql_ functions have been deprecated. That means the functions will be removed in future versions of php. You should use pdo or mysqli instead
2) When you store passwords in your database, they should always, always, always be encrypted.
Regarding your question, I think you are asking how to change the metadata (such as a firstname) without unsetting the photo url. Try something like this:
$updatequery = "UPDATE user SET firstname = '".$firstname."' , lastname = '".$lastname."' , password = '".$pwd."'";
if( $_FILES['photo_profile'])
{
$image = $foldername . basename ($_FILES['photo_profile'] ['name']);
$updatequery .= ", photo_profile='".$image."'";
}
$updatequery .= " where id_user ='".$_SESSION['id']."'";

i cannot compare matching passwords client and database for login?

i use from below code for login.
$sid = trim($_POST["id"]);
$pcode = trim(md5($_POST["pcode"]));
include_once "../conf.php";
$pdo = connect();
$sql_log = "select * from `manager` where `sid` = $sid limit 1";
$do_log = $pdo->prepare($sql_log);
$do_log->execute();
$num_log = $do_log->rowCount();
if($do_log){
if($num_log == 1){
while($row_log = $do_log->fetch()){
$pcode_db = $row_log["pcode"]; //md5 password
}
if(var_dump($pcode == $pcode_db)){ //or $pcode == $pcode_db, both return false
return true;
}else{
return false; // i get false for any password}
}
}
}
i can not login to right password! i set md5 password in database manually with phpmyadmin
I don't know why this works, but it did. I set md5 password (do md5 with PHP) in my database manually with phpMyAdmin(insert)!
structure column pcode >>varchar(32)
The md5 password has 32 characters, but when it's set from insert in phpMyAdmin, the pcode column only contains 31 characters... So I used SQL in phpMyAdmin for setting the md5 password!
update `manager` set `pcode` = MD5("my password") where `sid` = 7283
and then it is completely set to 32 characters. Could someone explain why this happens?
i set md5 password in database manually with phpmyadmin
MySQL MD5 is not the same algoritham as PHP MD5. You need to use one or the other.
Following code is just like your code but little change sql query.
$sid = trim($_POST["id"]);
$pcode = trim(md5($_POST["pcode"]));
include_once "../conf.php";
$pdo = connect();
$sql_log = "select * from `manager` where `sid` = $sid and `pcode` = $pcode";
$do_log = $pdo->prepare($sql_log);
$do_log->execute();
if($do_log){ // if incoming sid and pcod will match
return true;
}else{
return false;
}
I don't know how to work of your connect() function. Another way to connect sql is like that:
$sid = trim($_POST["id"]);
$pcode = trim(md5($_POST["pcode"]));
include_once "../conf.php";
mysql_connect('server_name','user_name','password');
mysql_select_db('DB_name');
$query = mysql_query("select * from `manager` where `sid` = $sid and `pcode` = $pcode");
if(mysql_fetch_array($query)){
return true;
}else {
return false;
}

Check record exists db - error show

How do I check if username or email exists and then put a error message in my error array. Right now i have:
$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0)
{
echo "That username or email already exists";
}
But I want to check if it is the username OR the email that is existing and then put:
error[] = "username is existing"; //if the username is existing
error[] = "email is existing"; //if the email is existing
How to do?
It would be easier if you just did a quick true/false check in the SQL and checked the flag that came back.
$sql = "SELECT "
. "(SELECT 1 FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "'), "
. "(SELECT 1 FROM `users` WHERE `email` = '" . mysql_real_escape_string($email) . "')";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
if ($foundFlags['username']) {
$error[] = "username is existing";
}
if ($foundFlags['email']) {
$error[] = "email is existing";
}
} else {
// General error as the query should always return
}
When it does not find an entry, it will return NULL in the flag, which evaluates to false, so the if condition is fine.
Note that you could generalise it for a field list like this:
$fieldMatch = array('username' => $username, 'email' => $email);
$sqlParts = array();
foreach ($fieldMatch as $cFieldName => $cFieldValue) {
$sqlParts[] = "(SELECT 1 FROM `users` WHERE `" . $cFieldName . "` = '" . mysql_real_escape_string($cFieldValue) . "')";
}
$sql = "SELECT " . implode(", ", $sqlParts);
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
foreach ($foundFlags as $cFieldName => $cFlag) {
if ($foundFlags[$cFieldName]) {
$error[] = $cFieldName . " is existing";
}
}
} else {
// General error as the query should always return
}
NB. Note that assumes all fields are strings, or other string-escaped types (eg. date/time).
Sounds like you're trying to let users know whether a username or email already exists at registration time. Here's what you can do:
<?php
//----------------------------------------
// Create first query
$usernameQuery = 'SELECT username FROM users WHERE username="'.mysql_real_escape_string($username).'"';
//----------------------------------------
// Query db
$usernameResult = mysql_query($userNameQuery);
//----------------------------------------
// Check if result is empty
if(mysql_num_rows($usernameResult) > 0){
//----------------------------------------
// Username already exists
$error[] = 'Username already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Check if email exists
//----------------------------------------
// Create query
$emailQuery = 'SELECT email FROM users WHERE email="'.mysql_real_escape_string($email).'"';
//----------------------------------------
// Query the db
$emailResult = mysql_query($emailQuery);
//----------------------------------------
// Check if the result is empty
if(mysql_num_rows($emailResult) > 0){
//----------------------------------------
// Email already exists
$error[] = 'Email already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Continue with registration...
}
}
?>
Please note that you should always escape your values before executing the actual query.
Additional Resources:
http://us.php.net/manual/en/function.mysql-real-escape-string.php
http://us.php.net/manual/en/function.mysql-escape-string.php
You can fetch one row and see if you got same email that you search or same username or both. You can do LIMIT 0,1 if you can stop after finding first row matching either this or that.

Categories