PHP Server-Side Validation of Related Fields - php

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;

Related

Reset password confirmation does not work properly?

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]);

PHP function (adding records) not working correct

I am working on a website which will have a user adding form. The following function is addrecord(). When the admin user is creating a new user, this function adds the rows in the SQL table. But, every time I add a new users, I stucked at the error message "User name/password not added to contact", at the first else statement. When I check the table, the access level and password fields are having the data, but I cannot log in with the hashed password. Anybody could help, what's wrong with this code?
Thanks,
Sixxdog
public function addRecord() {
// Verify the fields
if ($this->_verifyInput()) {
// prepare for the encrypted password
$password = trim($_POST['password1']);
// Get the Database connection
$connection = Database::getConnection();
// Prepare the data
$query = "INSERT INTO contacts(first_name, last_name, position, email, phone)
VALUES ('" . Database::prep($this->first_name) . "',
'" . Database::prep($this->last_name) . "',
'" . Database::prep($this->position) . "',
'" . Database::prep($this->email) . "',
'" . Database::prep($this->phone) . "')";
// Run the MySQL statement
if ($connection->query($query)) { // this inserts the row
// update with the user name and password now that you know the id
$query = "UPDATE contacts
SET user_name = '" . Database::prep($this->user_name) . "',
password = '" . hash_hmac('sha512',
$password . '!hi#HUde9' . mysql_insert_id(),
SITE_KEY) ."',
access = '" . Database::prep($this->access) . "'";
if ($connection->query($query)) { // this updates the row
$return = array('', 'Contact Record successfully added.', '');
// add success message
return $return;
} else {
// send fail message
$return = array('', 'User name/password not added to contact.', '');
return $return;
}
} else {
// send fail message and return to contactmaint
$return = array('contactmaint', 'No Contact Record Added. Unable to create record.', '0');
return $return;
}
} else {
// send fail message and return to contactmaint
$return = array('contactmaint', 'No Contact Record Added. Missing required information
or problem with user name or password.', '0');
return $return;
}
}
There's no WHERE clause in your update statement. Perhaps the user_name column has a unique index on it?

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.

Update query not working properly

Ok...I'm using a mySQL DB and this code snippet is part of a login process that is called from a flex coded swf
The code essentially does two things:
1) Checks for existance of a record and then checks period difference if that record exists
If the record exists and is older than six months it will do an update query
2) If no record exists it will use an insert
WHAT"S HAPPENNING...the insert works great...and the update query works except the values for Company and LastName are removed and no value is stored in the database
Why? That is the ten million dollar question...why is the update portion of this code not updating the Company and LastName fields?
Code Below
//This function handles the request from the Update Contact Information popup window in flex to update the records in the database
function updateContactInformation() {
//Initialize variable for result
$Result = false;
//ESTABLISH A CONNECTION WITH THE DATABASE
global $Return;
global $mysql;
global $username;
//ACQUIRE VALUES FROM THE HTTPS REQUEST(FLEX)
//mysql_real_escape_string is used to ensure no code is injected into the input fields
$uUCI_MSUN = mysql_real_escape_string($username); //value used in DB to associate login username with the users formal name
$uUCI_firstname = mysql_real_escape_string($_POST['firstname']);//first name of user
$uUCI_lastname = mysql_real_escape_string($_POST ["lastname"]);//last name of user
$uUCI_company = mysql_real_escape_string($_POST ["company"]);//Name of users company
$uUCI_email = mysql_real_escape_string($_POST["email"]); //email of the user
$uUCI_phone = mysql_real_escape_string($_POST["phone"]); //phone # of the user
//** Note: we do not collect time as the database will automatically update the Last_Updated_Date field with a new timestamp when the record is added or modified
//CHECK TO SEE IF A RECORD EXISTS FOR THE USER ***by checking number of rows returned in a query for login username
if(mysql_num_rows(mysql_query("SELECT MS_UserName FROM usercontactinformation WHERE MS_UserName = '" . $uUCI_MSUN . "'"))){
// UPDATE RECORD IN DATABASE
$query2 = "UPDATE usercontactinformation SET FirstName = '" . $uUCI_firstname . "', LastName = '" . $uUCI_lastname . "', Company = '" . $uUCI_company . "', Email = '" . $uUCI_email . "', Phone = '" . $uUCI_phone ."' WHERE idUserContactInformation = " . getUID($username) . " ;";
//send Request to mySQL
$Result = mysql_query($query2, $mysql);
} else {
//INSERT NEW RECORD INTO DATABASE
$query ="INSERT INTO usercontactinformation (MS_UserName,FirstName,LastName,Company,Email,Phone) VALUES('" . $uUCI_MSUN . "','" . $uUCI_firstname . "','" . $uUCI_lastname . "','" . $uUCI_company . "','" . $uUCI_email . "','" . $uUCI_phone . "');";
//send Request to mySQL
$Result = mysql_query($query, $mysql);
}
//RETURN A RESULT TO FLEX
if ($Result) {
$Return .= "<SuccessCode>1</SuccessCode>";
} else {
$Return .= "<SuccessCode>0</SuccessCode>";
}
}
function getUID($username) {
global $mysql; //access Global mysql connection
//Create Query to verify user exists and check difference between current date and Date Last Modified for the Users Contact Information
$query = "Select idUserContactInformation from mydatabasename.UserContactInformation where MS_username = '" . $username . "'";
//Send The Query To the SQL server
$result = mysql_query($query, $mysql);
//parse results and return access level to calling function
while ( $User = mysql_fetch_object( $result ) ) {
return $User->idUserContactInformation;
}
}
$Return .= "</Result>";
print ($Return)
Somone asked for the form values...the below code is a snippet from flex that passes the form value to the PHP file
public function useHttpService():void {
//Alert.show("Use HTTPS");
service = new HTTPService();
service.method = "POST";
service.useProxy = false;
service.url = parentApplication.relativeDir + "/somepath/phpfileprocessinginformation.php";
service.request.req = "updateContactInformation";
service.request.username = parentApplication.User.username;
service.request.password = parentApplication.User.password;
//pass user supplied new information to query
service.request.firstname = firstname.text;
service.request.lastname = lastname.text;
service.request.company = company.text;
service.request.email = email.text;
service.request.phone = phone.text;
service.addEventListener(ResultEvent.RESULT, httpResult);
service.addEventListener(FaultEvent.FAULT, httpFault);
service.send();
}
You have extra spaces in the two lines of code where you should be getting those values:
... $_POST ["lastname"]);//last name of user
... $_POST ["company"]);//Name of users company
That is not the same as:
... $_POST["lastname"]);//last name of user
... $_POST["company"]);//Name of users company
HTH.
Not a big PHP guy -- found this question when looking through the MySQL stuff -- so I'm not sure this is valid at all, but where you're setting the lastname and company variables you have a space between $_POST and the bracket ([), could that be the problem? (The other ones don't have the space.)

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