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";
}
Related
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;
}
}
}
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.
This is my code to validate email, it works great but I want if the email does not end with a .mil it says invalid email
if (isset($_POST['update_email'])) {
$email = escape($_POST['email']);
if (empty($email)) {
$errors[] = "Email Address Required.";
}
if (email_exists($email)) {
$errors[] = "Email Address in use.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = "Invalid Email Address";
}
if (! empty($errors)) {
echo validation_errors($errors[0]);
} else {
}
Thanks.
Add a regular expression conditional statement
if (!preg_match('/\.mil$/', $email) {
$errors[] = "Invalid Email Address";`
}
Or perhaps you can build this logic inside email_exists.
How can I put my validation codes into a function? How am I going to return it and call it? I am trying to call put them in just one code and then call them in a function for my forms. Any idea?
Here's my codes:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
$errors[] = "email cannot be blank";
}
if(empty($_POST['first_name']))
{
$errors[] = "First Name cannot be blank";
}
if(empty($_POST['last_name']))
{
$errors[] = "Last Name cannot be blank";
}
if(empty($_POST['password']))
{
$errors[] = "Password cannot be blank";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
$errors[] = "Birth Date cannot be blank";
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = $errors;
//redirect your user back using header('location: ')
header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
//redirect your user to the next part of the site!
}
}
So when I call this this wont work:
echo validate();
Hope you can help. Thanks!
So you're saying something like:
class Validation {
public static function emailFilter($input) {
global $_POST;
return empty($_POST['email']) AND filter_var($input,
FILTER_VALIDATE_EMAIL) != false ? "email cannot be blank" : false;
}
}
Or are you looking to do something else?
EDIT 1
Okay, how about:
function filter ($input, $type) {
if (!$input OR !$type) {
switch ($type) {
case "email":
// Check email
if (empty($_POST['email']) AND filter_var($input, FILTER_VALIDATE_EMAIL)) {
return "email cannot be blank";
}
break;
case "first_name":
if(empty($_POST['first_name']))
{
return "First Name cannot be blank";
}
break;
// And so on.
}
}
}
You could call it then by:
filter($_POST['email'], 'email');
So then:
if (!filter($_POST['email'], 'email')) {
// The email checks out.
} else {
$error[] = filter($_POST['email'], 'email');
}
There are will be more elegant solutions available, but this is based on what I think you want.
Let's say that the user clicks the button after filling-up the required fields, in your $_POST['submit'] or whatever name of your button, just add your codes, and print the error beside the html textbox by adding or if you want, just print $error below the textboxes of your html registration page. And if the errors return zero value, then you can add everything in the database then redirect to your desired page in the else block of your error checking codes.
I would do this like so:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
array_push($errors, "Email cannot be blank");
}
if(empty($_POST['first_name']))
{
array_push($errors, "First Name cannot be blank");
}
if(empty($_POST['last_name']))
{
array_push($errors, "Last Name cannot be blank");
}
if(empty($_POST['password']))
{
array_push($errors, "Password cannot be blank");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
array_push($errors, "Birth Date cannot be blank");
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = implode("|", $errors);
//redirect your user back using header('location: ')
return 0;
/*
Can't use both return & redirect, but return is more flexible.
*/
//header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
return array("email" => $email, "first_name" => $first_name,
"last_name" => $last_name, "password" => $password,
"birth_date" => $birth_date);
// so now you have your results in an associative array.
// you can use print_r(validate()); to see the results, or use
// $r = validate(); if ($r != false) { /*go places!*/}
//redirect your user to the next part of the site!
}
}
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...