email validation one condition & more than one else statement in PHP - php

I will try to put email validation with have more than one case.
First(if):email is required.
Second(if): invalid format of email.
Third(else): Email is exist(Active User)
Fourth(else): Email is in approve(Admin is not approved account yet so its
still in request table)
Fifth(else):Everything goes well,post the data into database.
I try to solve this by if-else statement but in last two case I do not have any condition its just have to pass that validation.I also try switch statement, but it's not go after the first case:
Here is my validation:
if(empty($_POST['email']))
{
$email=$_POST['email'];
$emailError="Email is required";
$error=true;
}
else
{
$email=$_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "Invalid email format";
$error=true;
}
else
{
$sql="SELECT * FROM user WHERE email='$email'";
$res=mysqli_query($db,$sql);
if (mysqli_num_rows($res) > 0)
{
$emailError = "Email already exists";
$error=true;
}
}
else
{
$sl="SELECT * FROM request WHERE email='$email'";
$ress=mysqli_query($db,$sl);
if (mysqli_num_rows($ress) > 0)
{
$emailError = "Your Accout is in process";
$error=true;
}
}
}

Following is the way to do this:
Declare some random variables for each error
By using the multiple if conditions make a first check if it is empty or not. Made a second check if it's match the correct format, third if value exist in db or not
I'm displaying the sample code for this
if(empty($_POST['email'])){
$emptyMail = 'Please provide the Email';
}else{
$notEmpty= 1;
}
if(!){ //check the preg match
wrongFromat = 'Please enter the Mail in correct format';
}else{
$correctFormat = 1;
}
if($notEmpty= 1 && $correctFormat = 1){ //check the database
//if it exist in db
$exist = 0;
}elseif($notEmpty= 0 || $correctFormat = 0 || $notEmpty= 1 || $correctFormat = 1){
$exist = 0;
}else{
$exist = 1;
}
if($notEmpty= 1 && $correctFormat = 1 $exist = 1){
//insert in database and send the status pending to the user
}

In line 1 you check if(empty($_POST['email'])),
so if it is empty you should return error, instead you try to save empty value in line 3 and so on.

ok I put the condition for $error & now its working fine. remember that you have to put $exist=""; in starting.
here is my code:
if(empty($_POST['email']))
{
$email=$_POST['email'];
$emailError="Email is required";
$error=true;
}
else {
$email=$_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "Invalid email format";
$error=true;
}
else
{
$sql="SELECT * FROM user WHERE email='$email'";
$res=mysqli_query($db,$sql);
if (mysqli_num_rows($res) > 0)
{
$emailError = "Email already exists";
$error=true;
$exist=1;
}
}
if($exist!=1)
{
$sl="SELECT * FROM request WHERE email='$email'";
$ress=mysqli_query($db,$sl);
if (mysqli_num_rows($ress) > 0)
{
$emailError = "Your Accout is in process";
$error=true;
}
}
}

Related

Sign in form validation in PHP

I am validating a sign in page form in PHP I have this code:
if($customerCount > 0) {
if(password_verify($password_2, $customer['password'])) {
if($customer['isEmailConfirmed'] == 0) {
$msg_2 = "<span class='text-danger'>Please verify your email!</span>";
} else {
$customer_id = $customer['id'];
login_2($customer_id);
}
} else {
$msg_2 = "<span class='text-danger'>The email address and password combination you provided was not found. Please try again.</span>";
}
} else {
$msg_2 = "<span class='text-danger'>The email address is not registered in our system.</span>";
}
And it works fine. But I need to add
if(empty($_POST['email_3']) || empty($_POST['password_3'])){
$msg_2 = 'You must provide email and password.';
}
If both email and password and left blank. Also I need to display message if email is filled but password blank and vice versa. Now how could I add these codes to my validation. I'm getting confused and lost about all these if statements. Where should I add these and how ??
<?php
// changed || to &&
if(empty($_POST['email_3']) && empty($_POST['password_3'])) {
$msg_2 = "<span class='text-danger'>You must provide email and password.</span>";
}
// No need to write this code.
else if(empty($_POST['email_3']) && !empty($_POST['password_3'])) {
$msg_2 = "<span class='text-danger'>Please enter a valid email address.</span>";
}
/*
You can write this code for validate email
else if(!empty($_POST['email_3']) && filter_var($_POST['email_3'], FILTER_VALIDATE_EMAIL) === false) {
$msg_2 = "<span class='text-danger'>Please enter a valid email address.</span>";
}
*/
else {
// Please write your remaining code
if($customerCount > 0) {
if(password_verify($password_2, $customer['password'])) {
if($customer['isEmailConfirmed'] == 0) {
$msg_2 = "<span class='text-danger'>Please verify your email!</span>";
} else {
$customer_id = $customer['id'];
login_2($customer_id);
}
} else {
$msg_2 = "<span class='text-danger'>The email address and password combination you provided was not found. Please try again.</span>";
}
} else {
$msg_2 = "<span class='text-danger'>The email address is not registered in our system.</span>";
}
}
?>
You can use a sequential algoritm. In this way it is easy to add a lot of validation, keeping the readability ok.
$everythingOk = true;
$errMessage = '';
if (empty($_POST['email_3']) {
$everythingOk = false;
$errMessage = 'Email 3 empty';
}
if ($everythingOk && empty($_POST['password_3']) {
$everythingOk = false;
$errMessage = 'Password 3 empty';
}
if ($everythingOk && ($customerCount === 0)) {
$everythingOk = false;
$errMessage = 'Customer count error';
}
........
if ($everythingOk) {
// all info ok, move on
} else {
// info is not valid
// message is in $errMessage
}
It might be easier to place it all into a function and return a result. The way you are doing your if statements you end up with a big V and makes it very hard to read at times:
<?php
$loginCheck = getLogin( $_POST , $customer , $password_2 );
if( is_array( $loginCheck ) ){ // if error messages are present
// Login errors
foreach( $loginCheck as $errorMsg ){
echo $errorMsg . '<br />';
}
}
if( $loginCheck ){ //assuming login_2 returns boolean true if logged in
echo 'Logged In!';
}
function getLogin( $details , $customer , $password ){
$errors[]; //set errors array to catch all errors
if(empty($details['email_3'])){
$errors[] = "You must provide an email.";
}
if(empty($details['password_3'])){
$errors[] = "You must provide a password.";
}
if( ! empty( $errors[] ) ){
//fatal error no point going futher
return $errors;
}
if( ! $customer ) { //assuming if no email is found $customer returns boolean
$errors[] = "<span class='text-danger'>The email address is not registered in our system.</span>";
}
if( ! password_verify( $password , $customer['password'] ) ) {
$errors[] = "<span class='text-danger'>The email address and password combination you provided was not found. Please try again.</span>"
}
if($customer['isEmailConfirmed'] === 0) {
$errors[] = "<span class='text-danger'>Please verify your email!</span>";
}
return login_2($customer['id']);
}
?>
Try this code:
<?php
if(empty($_POST['email_3'])) {
// Email is left blank
if(empty($_POST['password_3'])) {
// Password is also blank
$msg_2 = "You must provide email and password.";
} else {
// Only email is blank
$msg_2 = "You must provide email address.";
}
} elseif(empty($_POST['password_3']) && !empty($_POST['email_3'])) {
// Only password is blank
$msg_2 = "You must provide a password.";
}
}
// Your custom form validation goes here
?>
The first if checks whether the email is blank or not. The nested if checks meanwhile if the password is also blank. If this is the case, the message You must provide email and password. is assigned to $msg_2; otherwise this is You must provide email address..
The elseif checks if the password is empty AND if the email is not empty. If this is the case, the third message is put into $msg_2.

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

register for email address is unique

I want to validate the email address to make sure that it is unique.
By using the following code, it suppose to check the user input is not empty, is a valid email address and also it is not duplicated
but my code seem like doesn't work and gave me the following error.
i already go through the question that had been asked by other people but i still cnt solve the problem
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
boolean given in
I wonder is that my sequence of 'if' statement is wrong or what else?
any help please?
Here is my code
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$valid = false;
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} if($email != "") {
$result = mysqli_query($conn,"SELECT * FROM email where email='".$email."'");
$num_rows = mysqli_num_rows($result);
}if($num_rows >= 1){
$emailErr = "Email already in use";
$valid =false;
}
}
You should check the result (that is $result) of mysqli_query before passing it to mysqli_num_rows, see the documentation.
Make code easily maintainable for future use. I have updated your code, check this solution.
error_reporting(E_ERROR | E_PARSE);
$mysqli = new mysqli("localhost", "my_user", "my_password", "worldDB");
if (isset($_POST['submit']){
$email = $_POST['email'];
$emailErr = "Email is required";
if(!filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
$sql = "SELECT count(*) FROM emails where email='".$email."'";
$result = $mysqli->query($sql);
if($result->num_rows >= 1){
echo "email already exist";
} else {
$sql = "INSERT INTO emails (email) VALUES ('$email')";
$result = $mysqli->query($sql);
echo "Thank you for Submitting.";
}
}
else
{
$emailErr = "Invalid email format";
}
}
Hope this helps.

Exclude a specific email address from form submission

I have seen this question asked elsewhere but am unsure of how to put some validation into my particular form which will exclude a particular email address. I would like the form to be rejected if an email address is entered, lets say anything#anything.com. Please see code below. There is more but i believe this is the relevant part...
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){
foreach(array_keys($_COOKIE) as $value){
unset($_REQUEST[$value]);
}
}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 ||
stristr($_REQUEST['email']," ") ||
stristr($_REQUEST['email'],"\\") ||
stristr($_REQUEST['email'],":") ){
$errors[] = "Email address is invalid";
}
else{
$exploded_email = explode("#",$_REQUEST['email']);
if (empty($exploded_email[0]) ||
strlen($exploded_email[0]) > 64 ||
empty($exploded_email[1])){
$errors[] = "Email address is invalid";
}
else{
if(substr_count($exploded_email[1],".") == 0){
$errors[] = "Email address is invalid";
}
else{
$exploded_domain = explode(".",$exploded_email[1]);
if(in_array("",$exploded_domain)){
$errors[] = "Email address is invalid";
}
else{
foreach($exploded_domain as $value){
if(strlen($value) > 63 ||
!preg_match('/^[a-z0-9-]+$/i',$value)){
$errors[] = "Email address is invalid";
break;
}
}
}
}
}
}
}
If I understand your code, the goal of the main part is to validate the format of the email given by the user.
First of all, there is a built-in php function for this ( PHP >= 5.2 ) : filter_var(). You can replace all this block of code with :
$email = trim($_REQUEST['email']);
if (!filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Email address is invalid";
}
Then, if you want to check the email is not in a blacklist, just do something like this :
// Fill this array the way you want : hard-write it, fetch from database...
$blacklist = array("email1#gmail.com", "email2#gmail.com");
// Put in lower case for easiest comparison
$email = strtolower($email);
if (in_array($email, $blacklist)) {
$errors[] = "Email address is blacklisted";
}

Problem with my PHP server-side validation code

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...

Categories