PHP PDO statement that checks for existing username - php

currently working on an application and curious as to why my script is going to a blank page once I submit my form. It started occurring when I added a piece to my script that is supposed to go into my database that checks if a username exists and then echos a message if that is the case and echos a message if it isn't the case.
This is the code:
function validateUser() {
global $user, $userErr, $validForm;
$userErr = "";
if ($user == "") {
$userErr = "nothing entered";
$validForm = false;
}
else if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-
Z]*)*$/",$user)) {
$userErr = "invalid characters";
$validForm = false;
}
elseif (strlen($user) > 1) {
$stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
username = :username");
$stmt->bindValue(':username', $user);
$stmt->execute(array($user));
$norows = $result->fetchColumn();
if ($norows > 0 ) {
$userErr = 'Username already taken';
}
else {
$userErr='User added';
}
}
}
The bit that is giving me trouble is the last elseif statement... for some reason it hasn't been doing what it's supposed to do. I've looked at many different sources and I've tried implementing different solutions but nothing has seemed to work. This function runs when the form is submitted just incase you are wondering. Very open to any possible solutions you may have. Because I just can't get it to work... thanks!

Don't Use else if() since you are using different comparison statements. Just replace all your else if() with if() only. Then use $userErr variable to check if the inputs pass all your validations.
function validateUser() {
global $user, $userErr, $validForm;
$userErr = "";
if ($user == "") {
$userErr = "nothing entered";
$validForm = false;
}
if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/",$user)) {
$userErr = "invalid characters";
$validForm = false;
}
if (strlen($user) > 1) {
$stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
username = :username");
$stmt->bindValue(':username', $user);
$stmt->execute(array($user));
$norows = $result->fetchColumn();
if ($norows > 0 ) {
$userErr = 'Username already taken';
}
}
if($userErr == "") {
$userErr='User added';
}
}

Related

I wonder a php 7.4 giving me trouble on login script

Problem is occurring when no user exists because PHP 7.4 returns false here on $fetched = $check->fetch();
so how to handle this situation
$name = $_POST['name'];
$pass = $_POST['pass'];
$check = $db->prepare("SELECT id, name, pass FROM users WHERE name = ?");
$check->execute([$name]);
$fetched = $check->fetch();
if (password_verify($pass, $fetched['pass']) && ($name === $fetched['name']){
header('Location: home');
} else {
echo 'This account not exists';
}
but I don't know why this work without password_verify(), look
if ($check->rowCount() > 0 ) {
} else {
}
Add a check for $fetched:
if ($fetched && password_verify($pass, $fetched['pass'])) {
header('Location: home');
} else {
echo "Invalid username or password";
}
There's no need to test $fetch['name']. It's guaranteed to be equal to $name because of WHERE name = ?

how to validate one variable either of two variables in php

i have two variables mobile and email now i want to validate both but i want the user to leave blank one of the fields if user does not have one for ex if a user does not want to register with his email then he can go to mobile number for registration and vice versa this is my validation code
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$mobileerror = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$mobile = strip_tags($_POST['mobile']);
$fullname_valid = $email_valid = $mobile_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
if ($mobile) {
$query4 = "SELECT mobile FROM users WHERE mobile = '$mobile'";
$fire4 = mysqli_query($con, $query4) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire4) > 0) {
$mobileerror = "is already taken please try another one<br> ";
} else {
$mobile_valid = true;
}
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && ($email_valid || $mobile_valid )&& $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs how to solve this problem
Use one more flag
$isValid_email_mobile = FALSE;
When control flow enters into if (filter_var($email, FILTER_VALIDATE_EMAIL)) then on SUCCESS just set $isValid_email_mobile = TRUE; It will be same if control enters in condition if ($mobile) again on SUCCESS , set it as $isValid_email_mobile = TRUE;
When $isValid_email_mobile = FALSE; becomes TRUE then you know that of the field/variable has passed your requirement and its ready for DB INSERT
Then
In your last IF condition when you try to INSERT just change IF condition to the following
IF ($fullname_valid && $isValid_email_mobile && $password_valid && $username_valid)
One more thing whenever you are using Flag logic always set your flag to some default value before using it.
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs
you have:
if (!empty($fullname)) {}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {}
if ($mobile) {}
if (!empty($username)) {}
if (!empty($password)) {}
To remove the error, try adding
if (!empty($mobile)) {
Also, I would suggest to wrap the statements a bit more. You only need one to fail in order to stop input. You could do something like this:
$mobileOrEmail = false;
if (!empty($fullname) && !empty($username) && !empty($password) {
//check fullname, username and password
if (!empty($mobile) {
//check mobile, if it passes
$mobileOrEmail = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//check email, if it passes
$mobileOrEmail = true;
}
if (!$mobileOrEmail) $errors++;
} else {
//missing input values
$errors++;
}
Personally, I would create a function for each input field.
function checkUsername($username){
//check username
return true;
}
function checkEmail($email) {
//check email
return true;
}
....
then you can run
if (checkUsername($username) && checkPassword($password)
&& checkFullname($fullname) && (checkEmail($email) || checkEmail($email)) {
//user input correct
} else {
//user input failed
}
Just to give it more structure

validating if username already exists in database by using prepared statements... how to?

I am trying to validate username to assure that same username does not already exist in my database. I am trying to do so using prepared statements.
What I am trying to do right now is to see if post exist by checking what STMT has returned. I'm not really sure if I'm going into right direction with this.
What am I doing wrong?
EDIT: Although I tried what someone suggested and I am still adding duplicate username into database.
if (empty($username))
{
$usernameError = "Required!";
}
else if (preg_match('/^[A-Z \'.-]{2,20}$/i', $username))
{
if ($stmt1 = $dbc->prepare("SELECT username FROM users WHERE username = ?"))
{
$stmt1->bind_param('s', $username);
$stmt1->execute();
if($stmt1->num_rows>0)
{
$usernameError = "Username already exists!";
}
else
{
$usernameError = "";
}
$stmt1->close();
}
}
else
{
$usernameError = "Incorrect Username!";
}
Instead of using if($stmt != FALSE) use if($stmt->num_rows>0)
if($stmt->num_rows>0){
$usernameError = "Username already exists!";
}else{
$usernameError = "";
}
Using fetch() method works.
(posting because can't delete question with an answer)
if($stmt->fetch())
{
$usernameError = "Username already exists!";
}
else
{
$usernameError = "";
}

usercake updating field isn't working

I use User Cake for user management system but I am struggling with one problem, I have had asked this question in their website but I couldn't find anyone to help me out.
What I need is simply making the users be able to update their information. ex. first name, phone, email....The email field updates correctly as it came with that functionality.
The fields that I added aren't being updated. Can someone give me some hints on what I am missing?
Here is what I tried looking at the email field. I have First Name field.
Funcs.php
//Update a user's email
function updateEmail($id, $email)
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
email = ?
WHERE
id = ?");
$stmt->bind_param("si", $email, $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
//Update a user's first name. This is what isn't working.
function updateFirstname($id, $firstname)
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
firstname = ?
WHERE
id = ?");
$stmt->bind_param("si", $firstname, $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
Here is class.user.php
class loggedInUser {
public $email = NULL;
public $hash_pw = NULL;
public $user_id = NULL;
public $firstname = NULL;
//Update a users email
public function updateEmail($email)
{
global $mysqli,$db_table_prefix;
$this->email = $email;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
email = ?
WHERE
id = ?");
$stmt->bind_param("si", $email, $this->user_id);
$stmt->execute();
$stmt->close();
}
//Update a users first name
public function updateFirstname($firstname)
{
global $mysqli,$db_table_prefix;
$this->firstname = $firstname;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
firstname = ?
WHERE
id = ?");
$stmt->bind_param("si", $firstname, $this->user_id);
$stmt->execute();
$stmt->close();
}
}
user_settings.php where I can change the fields and hit the update button. If I change the email and hit update, the email is updated but when I change firstname and hit update I get
nothing to update
//Prevent the user visiting the logged in page if he is not logged in
if(!isUserLoggedIn()) { header("Location: login.php"); die(); }
if(!empty($_POST))
{
$errors = array();
$successes = array();
$password = $_POST["password"];
$password_new = $_POST["passwordc"];
$password_confirm = $_POST["passwordcheck"];
$errors = array();
$email = $_POST["email"];
$firstname = $_POST["firstname"];
//Perform some validation
//Feel free to edit / change as required
//Confirm the hashes match before updating a users password
$entered_pass = generateHash($password,$loggedInUser->hash_pw);
if (trim($password) == ""){
$errors[] = lang("ACCOUNT_SPECIFY_PASSWORD");
}
else if($entered_pass != $loggedInUser->hash_pw)
{
//No match
$errors[] = lang("ACCOUNT_PASSWORD_INVALID");
}
if($email != $loggedInUser->email)
{
if(trim($email) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
}
else if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
else if(emailExists($email))
{
$errors[] = lang("ACCOUNT_EMAIL_IN_USE", array($email));
}
//End data validation
if(count($errors) == 0)
{
$loggedInUser->updateEmail($email);
$loggedInUser->updateFirstname($firstname);
$successes[] = lang("ACCOUNT_EMAIL_UPDATED");
}
}
if ($password_new != "" OR $password_confirm != "")
{
if(trim($password_new) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_NEW_PASSWORD");
}
else if(trim($password_confirm) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_CONFIRM_PASSWORD");
}
else if(minMaxRange(8,50,$password_new))
{
$errors[] = lang("ACCOUNT_NEW_PASSWORD_LENGTH",array(8,50));
}
else if($password_new != $password_confirm)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
//End data validation
if(count($errors) == 0)
{
//Also prevent updating if someone attempts to update with the same password
$entered_pass_new = generateHash($password_new,$loggedInUser->hash_pw);
if($entered_pass_new == $loggedInUser->hash_pw)
{
//Don't update, this fool is trying to update with the same password ¬¬
$errors[] = lang("ACCOUNT_PASSWORD_NOTHING_TO_UPDATE");
}
else
{
//This function will create the new hash and update the hash_pw property.
$loggedInUser->updatePassword($password_new);
$successes[] = lang("ACCOUNT_PASSWORD_UPDATED");
}
}
}
if(count($errors) == 0 AND count($successes) == 0){
$errors[] = lang("NOTHING_TO_UPDATE");
}
}
if($email != $loggedInUser->email)
{
if(trim($email) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
}
else if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
else if(emailExists($email))
{
$errors[] = lang("ACCOUNT_EMAIL_IN_USE", array($email));
}
//End data validation
if(count($errors) == 0)
{
$loggedInUser->updateEmail($email);
$successes[] = lang("ACCOUNT_EMAIL_UPDATED");
}
}
Clone this function as
if($firstname != $loggedInUser->firstname) blah blah
Remove this line from the function above move it in the new function:
loggedInUser->updateFirstname($firstname);
Just clone the function,just as you have done above.Change the error messages and add function to validate the name,it will be somewhat different,it will require more work.

php user login anf function

if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if(empty($username) || empty($password)) {
$error = 1;
$error_message = 'Please fill in all the required fields.';
} else {
get_login_name($username, $password);
//The commented line works...
//$query = mysql_query("SELECT /* user_logged true, page login */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1");
}
if(mysql_num_rows(get_login_name($username, $password)) == 0) {
echo get_login_name($username, $password);
$error = 1;
$error_message = 'Incorrect username or password.';
} elseif ($error == 0) {
//Other stuff....
}
}
Function:
function get_login_name($password, $username) {
global $myDB;
global $config;
$query = "SELECT /* page == login, functions.php */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1";
$result = $myDB->Execute($query) or die(GetDbError($myDB->ErrorMsg()));
return $result;
}
How properly check if username or password incorrect ? (part if(mysql_num_rows(g.....)
In my opinion something wrong i have done ir function get_login_name with return and checking. By the way, using adodb.
EDIT:
After all i decided a bit test it, so, let's leave function as it now and let's check username and password part:
if (!is_null(get_login_name($password, $username))) {
echo get_login_name($password, $username);
$error = 1;
$error_message = 'Incorrect username or password.';
}
If username or password incorrect ir gives me:
username,password which mean result doesn't found at all (no user, if user correct gives same)
Ok, let's enter valid user and pass, and it gaves:
username,password zero,0a706ce75f3bc195c8ed7be5a21d3766abb0d384
What's wrong ?
Essentially, if get_login_name has a return, that means the query returned a match for username and password which means the combination is correct, otherwise, no result means there's no match so you could say either username or password is incorrect (because they don't exist or one of them is wrong). If $Result has a value using get_login_name would likely to be just:
if (!is_null(get_login_name($password, $username)))
// correct
else
// incorrect
Play around with it and see the results.
Ech, after testing managed it to work :)
That seems this part fails :/
if (!is_null(get_login_name($password, $username)))
So, hole code:
if (!$myDB->Affected_Rows()) {
//if(mysql_num_rows($query) == 0) {
$error = 1;
$error_message = 'Incorrect username or password.';
}
What i have ? Just changed it to:
if (!$myDB->Affected_Rows()) {
Thank you all guys who tryed help.

Categories