I have some php validation for a user signup form. It's validating all the input then if all is correct the else at the end, checks to see if that username is in use and if not creates that record in the database. For some reason the last else doesn't get activated and it just refreshes with all the data still in the input boxes. I can't find the problem anywhere!!
if(isset($_POST['user']))
{
$firstname = sanitiseString($_POST['firstname']);
$surname = sanitiseString($_POST['surname']);
$user = sanitiseString($_POST['user']);
$pass = sanitiseString($_POST['pass']);
$email = sanitiseString($_POST['email']);
$dateOfBirth = sanitiseString($_POST['dateOfBirth']);
$gender = sanitiseString($_POST['gender']);
$test_arr = explode('-',$dateOfBirth);
if($firstname == "" || $surname =="" || $user == "" || $pass == "" || $email == "" || $dateOfBirth == "" || $gender == "")
{$error = "Not all fields were entered</br></br>";}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{$error = "Email format invalid</br></br>";}
else if(count($test_arr) == 3)
{
if (!checkdate($test_arr[0], $test_arr[1], $test_arr[2]))
{$error = "Enter a date in the format: MM-DD-YYYY</br></br>";}
}
else if(count($test_arr) <> 3)
{$error = "Enter a date in the format: MM-DD-YYYY</br></br>";}
else
{
$result = querySQL("SELECT * FROM members WHERE user='$user'");
if($result->num_rows)
{$error = "That Username already exists</br></br>";}
else
{
querySQL("INSERT INTO members VALUES('','$firstname','$surname','$user','$pass','$email','$dateOfBirth','$gender')");
die("<h4>Account Created</h4>Please Log In.</br></br>");
}
}
}
First thing to comment on is the incredible amount of nested logic this script has; it's not uncommon to lose control of the flow when you're if / else branching gets out of control.
Example Restructure
if (isset($_POST['user']))
{
// Prep
$error = '';
// Sanitize
foreach( $_POST as $varName => $value )
{
// Doing this for minification on Stackoverflow
$$varName = sanitiseString($_POST[$varName]);
// Validate
if ( empty($$varname) )
$error .= "Not all fields were entered<br /><br />";
}
// Valid Email?
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= "Email format invalid<br /><br />";
// Validate date
$dateArray = explode('-', $dateOfBirth);
if (!checkdate($dateArray[0], $dateArray[1], $dateArray[2]))
{
$error .= "Enter a date in the format: MM-DD-YYYY</br></br>";
}
$result = querySQL("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
{
$error .= "That Username already exists</br></br>";
}
if ( !empty($error) )
die($error);
querySQL("INSERT INTO members VALUES('','$firstname','$surname','$user','$pass','$email','$dateOfBirth','$gender')");
die("<h4>Account Created</h4>Please Log In.</br></br>");
}
Some other things to note are conflicting logic with your count($test_arr) == 3 and count($test_arr) <> 3. And the value of $result->num_rows may not be 0, as your expecting.
Related
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
I am currently programming php, and enjoying it.
I know how to code a script that will update a user's email address or password in different processes. I need to update them in one form. Here's a screenshot:
I need to update one of them, if he didn't enter a password then update the email, if he didn't enter the email update the password, if he entered both update both..
the script I am currently coding has been twirling around my mind and I have lost myself over and over and over...
update_settings_process.php: (I have Updated the script!!)
<?php
error_reporting(1);
session_start();
include("../common/config.php");
include("../common/conn.php");
$case = '';
$error_str = '';
//email:
$email = stripslashes($_REQUEST['email_address']);
//password:
$old_password = trim($_REQUEST['old_password']);
$password = trim($_REQUEST['password']);
$conf_password = trim($_REQUEST['conf_password']);
$get_users_qry = "Select password From users where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."' AND password = '".md5($old_password)."' AND status = 1";
$get_users = $db->get_row($get_users_qry,ARRAY_A);
$qry = "Select email from users where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
echo 'Email:' . $email;
echo '<p>';
echo 'Old Password: '. $old_password;
echo '<p>';
echo 'Password:' . $password;
echo '<p>';
echo 'Confrim Password:' . $conf_password;
echo '<p>';
if(filter_var($email, FILTER_VALIDATE_EMAIL) && (strlen($password) > 5) && $get_users && !mysql_num_rows($res))
{
//update email and password
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo 'Email and Password Has been Updated!';
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "There is nothing to update";
echo $error_str;
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "Use a secure Password";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && (strlen($password) < 5))
{
$error_str .= "Password must be atleast 5 characters";
echo $error_str;
$case = 0;
die();
}
else
{
if ($email == '' && $password != $conf_password)
{
$error_str .= "Passwords Do not Match";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && !$get_users)
{
$error_str .= "Please enter correct old password <br>";
echo $error_str;
$case = 0;
die();
}
else
{
//update password only!
if(strlen($password) == 0)
{
die();
}
else
{
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Password changed successfully";
exit();
}
}
}
}
}
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
if($case = 0)
{
echo $error_str;
die();
}
?>
I have really lost myself in there, and I couldn't figure out why because of that..
I have updated the script:
it can update password and email at the same time
it can update password only
it can not update email only.. <-- im stuck here
here's the update email only part:
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
There are some mistakes in your if-clauses. Try changing them to something like this:
$email == ''
1) = is the assignment operator, == is the comparison operator, which you weirdly used correctly with the strlen($password) comparison. The mnemonic is "Twice is for T(w)sets, Once is for Owssignment" (works best in a North English accent).
2) You're doing something rather odd with the strlen() function. strlen() always returns an integer (until someone invents half-letters). Consequently, strlen == '' is a bad, bad test. What you would want that line to look like is this:
if ($email = '' && (strlen($password) == 0))
(though why you didn't use strlen() both times puzzles me!)
3) Do not, not even jokingly, use the word 'retard' in code, or at least be bright enough not to post it publicly. It's ableist and, frankly, stupid. There are loads of people on this board who are extremely experienced and would, were they not better (wo)men, think you to be one for using a single = to test. Never call your users, or indeed anyone, a 'retard'. It's not funny.
What is the wrong in my code. it's say... (1) Username required (2) Password is not correct if i click Log in button without username and password, but it' should be show All filed required.
<?php
if(isset($_POST['action']) && isset($_POST['action']) == "Sign in")
{
include("../secure/content/database/db.php");
$uname = mysql_real_escape_string(trim($_POST['uname']));
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
/// check user name
$sql = mysql_query("SELECT uname FROM members WHERE uname = '$uname'");
$num_u = mysql_num_rows($sql);
// check user password
$sql2 = mysql_query("SELECT pass FROM members WHERE pass = '$pass'");
$num_p = mysql_num_rows($sql2);
$err = array();
if(isset($uname) && isset($pass))
{
if( empty($uname) && empty($pass))
{
$err[] = "All field required";
}
else
{
if(empty($uname))
{
$err[] = "Username required";
}
else
{
if($num_u == 0) $err[] = "Username is not correct";
}
if(empty($pass))
{
$err[] = "Password required";
}
else
{
if($num_p == 0)
$err[] = "Password is not correct";
}
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red>$er</font><br>";
}
}
else
{
include("content/include/newsession.php");
$tm = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$rt = mysql_query("insert into plus_user_login(id,uname,ip,tm, status, tm_out) values ('$_SESSION[id]','$_SESSION[uname]','$ip','$tm', 'ON', '')");
echo mysql_error();
print "<script>";
print " self.location='content/index.php';";
print "</script>";
}
}
}
Any idea or Solution..
On this line:
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
You are calling md5() which will always return a value, even if $_POST['pass'] was empty. So empty($pass) will never be true.
The md5() sum of an empty string or NULL does not result in an empty value, so you always have a value in $pass, even if $_POST['pass'] was empty.
// Never empty
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
// Because:
var_dump(md5(""));
string(32) "d41d8cd98f00b204e9800998ecf8427e"
When you check for the presence of $uname & $pass, use the $_POST values instead:
// instead of
if( empty($uname) && empty($pass))
// do
if(empty($uname) && empty($_POST['pass']))
please remove this md5 from following line, md5 create a string if pass is empty.
md5(mysql_real_escape_string(trim($_POST['pass'])));
use this.
mysql_real_escape_string(trim($_POST['pass']));
use md5 in another.
Your are running into this problem because empty strings are hashable see this.
Change
if(isset($uname) && isset($pass))
to
if(isset($uname) && isset($_POST['pass']))
I'm trying to figure out how to find out where I need to do the steps if it was the username or if it was the email address the user filed out.
// Assign variable values if there is values
if ((isset($_POST['username'])) && ($_POST['username'] !== NULL) && (!empty($_POST['username']))) { $username = trim($_POST['username']); }
if ((isset($_POST['email'])) && ($_POST['email'] !== NULL) && (!empty($_POST['email']))) { $email = trim($_POST['email']); }
// IF BOTH FIELDS ARE EMPTY, ERROR CONDITION EXISTS
if (empty($username) && empty($email)) {
$errors = "yes";
$message = "You must enter a value for either the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else if (!empty($username) && !empty($email)) {
$errors = "yes";
$message = "You can only enter a value for the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
}
// Assign variable values if there is values
if ((isset($_POST['username'])) && ($_POST['username'] !== NULL) && (!empty($_POST['username']))) { $username = trim($_POST['username']); }
if ((isset($_POST['email'])) && ($_POST['email'] !== NULL) && (!empty($_POST['email']))) { $email = trim($_POST['email']); }
// IF BOTH FIELDS ARE EMPTY, ERROR CONDITION EXISTS
if (empty($username) && empty($email)) {
$errors = "yes";
$message = "You must enter a value for either the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else if (!empty($username) && !empty($email)) {
$errors = "yes";
$message = "You can only enter a value for the username or email address!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
if(!empty($username)) {
//Do some things if the user entered only the username
}
else {
//Do some things if the user entered only email
}
}
else if ( empty( $username ) ) {
// Output username error
}
else if ( empty( $email ) ) {
// Output email error
}
In this case, however, I would skip the if/else statements, and just use an error condition:
$is_error = false;
if ( empty( $username ) ) {
$is_error = true;
$error_messages[] = 'Your username error message';
}
if ( empty( $email ) ) {
$is_error = true;
$error_messages[] = 'Your email error message';
}
if ( $is_error ) {
// Output all error messages
}
else {
// Perform success event
}
I think you need to do your steps in the last else that will execute only if neither username and email are empty or inputted. So in the last else, you can do something like
if (!empty($username)) {
} else {
}
On another note, I think you do not need to all the 3 checks when populating $username or $email; the first and the last should suffice, like:
if (isset($_POST['username']) && !empty($_POST['username']) {
$username = $_POST['username'];
}
I have a form in a file register.php, and it posts to registerPost.php. Inside registerPost.php, I check against a few validation rules, then if any of them are flagged, I return to the first page and print the errors. In theory, that should work. But the validation goes through with no problems, even when I leave everything blank.
Here's the code in question:
$_SESSION["a"] = "";
$_SESSION["b"] = "";
$_SESSION["c"] = "";
$_SESSION["d"] = "";
$_SESSION["e"] = "";
$_SESSION["f"] = "";
$_SESSION["g"] = "";
if(empty($userEmail))
{
$_SESSION["a"] = "You must enter your email.";
}
if(!validEmail($userEmail))
{
$_SESSION["a"] = "Improper Email Format";
}
if(empty($password))
{
$_SESSION["b"] = "You must enter a password.";
}
if(strlen($password) < 5 || strlen($password) > 0)
{
$_SESSION["b"] = "Password must be at least 5 characters.";
}
if($password != $confPassword)
{
$_SESSION["c"] = "Passwords do not match";
}
if(empty($firstName))
{
$_SESSION["d"] = "First Name Required";
}
if(empty($lastName))
{
$_SESSION["e"] = "Last Name Required";
}
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '$email'")) > 0)
{
$_SESSION["f"] = "This email address already exists in our database.";
}
if(!empty($_SESSION["a"]) || !empty($_SESSION["b"]) || !empty($_SESSION["c"]) || !empty($_SESSION["d"]) || !empty($_SESSION["e"]) || !empty($_SESSION["f"]))
{
header('Location: register.php');
}
Perhaps there is a more straightforward way to do this?
I like this way of registering all errors:
$errors = array();
if (empty($foo1))
$errors[] = "foo1 can't be left blank!";
else if (!preg_match(' ... ', $foo1))
$errors[] = "foo1 was not filled out correctly!";
if (empty($foo2))
$errors[] = "foo2 can't be left blank!";
// ...
if (empty($errors)) {
// do what you need
} else {
// notify the user of the problems detected
}
Do you really need to change the page by header?
I tried your code and it works for me.
Guessing from $username,$email and so on, I think you're doing some sanitizing on the $_POST data. If so, you should dump the $username, etc. to see, if that procedure is putting something in these variables.
Anyway, I like this way of validation better:
$errors = array();
if(empty($username))
{
$errors['username'] = 'Username cannot be empty!';
}
...
$_SESSION['errors'] = $errors;
if(count($errors) > 0) //Redirect...