Received Array From one Input Field How Can Validate it? - php

I want to get ten emails from user.how to check the user provide the correct email or not ? i am try multiple methods but failed to check it please help.
for($i=1;$i<=9;$i++)
{
echo "<input type='text' value='' name='email[]' class='form-control'>"."</br>";
}
// Php Code
// Step One Catch The Values
$email = $_POST['email'];
// Unset the empty values from array
foreach($email =>$key as $emails){
if($emails == ""){
unset($email[$key]);
}
}
Here I am successfully done But when i try to validate it it return me errors which i was never face.
I want to remove html special character from input field and also validate my input using filter_var for email validation. I am trying to do it with loop through method but does not work.

To achieve that look over below code. As you are receiving the array of email as an input from the end user.
if(count($_POST['email']) > 0)
{
$pattern = "/^\[?[0-9\.]+\]?$/";
foreach($_POST['email'] as $email)
{
if (preg_match($pattern, $email) === 1) {
// emailaddress is valid
}
}
}

You are writing foreach wrong way. try below code
foreach($email as $key=>$emails)
{
if($emails == "")
unset($email[$key]);
}

The easiest and safest way to check whether an email address is well-formed is to use the filter_var() function:
if(count($_POST['email']) > 0)
{
$email = $_POST['email'];
foreach($email as $key => $emails)
{
if(!filter_var($emails, FILTER_VALIDATE_EMAIL))
{
//invalid email
unset($email[$key]);
}
else
{
//valid email
}
}
}

Related

Verifying multiple emails from array

I have a query that I am not too sure how I can make it work
I have a form where the end users can add multiple email fields using jquery and it places each text input into an array
I have created some code that verifies each array key and fills an array with a number for verification purposes
Here is the code for verifying the POST:
// Collect and verify attached email
if(isset($_POST["email"])){
// set var for collecting email and store as null
$emailfields ="";
// start verify loop
foreach($_POST["email"] as $key => $email)
{
// Filter var email to comfirm it is an email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
$emailcheckarray[] = 1;
} else {
$emailcheckarray[] = 0;
}
// Create a string for later
$emailfields .= $email .",";
}
// Verify Array contains value
if (!in_array('1', $emailcheckarray, true))
{
$emailverification = 1;
} else {
$emailverification = 0;
}
}
echo $emailfields;
echo $emailverification;
Now this works it fills the array $emailcheckarray with 1 1 1 1 1 if the emails are valid depending on how many inputs the user uses.
Is there a way that I can get the in_array to only work with all keys being the same as currently if one of the keys are 0 it still outputs $emailverification as 1 if the user enters 1 valid email and the rest invalid when I want it to be 0.
You can just omit the in_array if you set the verification to 0 during the loop when any of the checks fails. So start with a value of 1 as you have no failures yet:
$emailverification = 1; // added
// start verify loop
foreach($_POST["email"] as $key => $email)
{
// Filter var email to comfirm it is an email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false)
{
$emailcheckarray[] = 1;
} else {
$emailcheckarray[] = 0;
$emailverification = 0; // added
}
// Create a string for later
$emailfields .= $email .",";
}
... and then at the end of the loop you have the correct value.
You can use functions such as array_map and array_filter to get an array of all the valid emails.
if (isset($_POST['email'])) {
$sanitized_emails = array_map(function ($email) {
return filter_var($email, FILTER_SANITIZE_EMAIL);
}, $_POST['email']);
$valid_emails = array_filter($sanitized_emails, function($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
});
$emailfields = implode(',', $sanitized_emails);
}
Then you just have to compare the size of the two tabs.
$emailverification = 0;
if (count($emails) == count($valid_emails)) {
$emailverification = 1;
}
Check the affirmative for zero:
if (in_array('0', $emailcheckarray, true)) {
$emailverification = 0;
} else {
$emailverification = 1;
}
If you don't have any zeros, that means they're all ones.

Php how to use multiple parameters

there are two parameters in my app, user will fill one of them, but two parameters will get posted into php,php should select non empty field and do some action! something like this.point me right direction. i think 'isset get' should not be used three times like that right?which statement to be used 'and' or 'or' statement.?
i know it's stupid question! i appreciate ur help.
if (isset($_GET['Email']) && !empty($_GET['Fax'])) {
echo "fax is empty and Email = ".$_GET['Email'];
} elseif (isset($_GET['Fax']) && !empty($_GET['Email'])) {
echo "email is empty and Fax = ".$_GET['Fax'];
} elseif (!empty($_GET['Fax']) && !empty($_GET['Email'])) {
echo "Fax and email is empty";
} else {
echo"empty";
}
Simpler version:
$email = isset($_GET['Email']) ? $_GET['Email'] : null;
$fax = isset($_GET['Fax']) ? $_GET['Fax'] : null;
if (empty($email)) {
// email empty
}
if (empty($fax)) {
// fax empty
}

PHP- Validate on certain fields

I've a form,in the form only few fields are mandatory.When a fields is not mandatory,it should not check for empty data validation.If the non mandatory field contain data then it shoudl check the data,validation should happen only when data present.
My below code check for all fields.For eg:Say phone is not mandatory in below code,how to change the code.
$validate = array(
array($x, '/^[a-z\d ]{4,20}$/i', "Please enter valid name."),
array($y, '/^[a-z\d ]{4,20}$/i', "Please enter a real category."),
array($phone, '/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/' , "Please enter a valid phone number")
);
$error = '';
foreach ($validate as $validation)
{
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
if($error != '')
{
echo $error;
exit;
}
Comment on this post,if it is not clear.
Thanks in advance!
If you want to check if at least required fields have been submitted, you can check whether they have been set and have a truthy value using the isset and empty functions.
For example:
if ( isset($_POST['username'], $_POST['password']) &&
! empty($_POST['username']) && ! empty($_POST['password']) ) {
// validation here
}
That would check if the username and password fields were submitted and have a value, whereas for example an email field wouldn't necessarily have been filled in for the above condition to return true.
If you know the mandatory fields before hand I'll suggest you group them in an array and test for based on the current key. If a key is in not mandatory but holds value you can test otherwise do your regular check.
$error = '';
$mandatoryFields = array('key1', 'key2' 'key3');
foreach ($validate as $validation)
{
if (!in_array($validation[0], $mandatoryFields) && strlen(trim($validation[0])) > 0)
{
// There is data in a non mandatory field.
// Perform your test.
}
else {
// Do your regular test.
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
}
You can give this a try.

Remove specific definitions from a variable in PHP

I have a PHP mail script that validates name, email address, and phone number before sending the mail. This then means that the Name, Email address, and Phone fields are Required Fields.
I want to have it so that the Name and EITHER Email or Phone are required. Such that if a name and phone are inputted, it sends the mail, or if a name and an email are inputted, it also sends the email.
The way the script works right now is it has several IF statements that check for (1) name, (2) email and (3) phone. Here's an example of an if statement of the code:
if ( ($email == "") ) {
$errors .= $emailError; // no email address entered
$email_error = true;
}
if ( !(preg_match($match,$email)) ) {
$errors .= $invalidEmailError; // checks validity of email
$email_error = true;
}
And here's how it sends the mail:
if ( !($errors) ) {
mail ($to, $subject, $message, $headers);
echo "<p id='correct'>";
echo "ההודעה נשלחה בהצלחה!";
echo "</p>";
} else {
if (($email_error == true)) {
$errors != $phoneError;
/*echo "<p id='errors'>";
echo $errors;
echo "</p>";*/
}
if (($phone_error == true)) {
$errors != $emailError;
$errors != $invalidEmailError;
/*echo "<p id='errors'>";
echo $errors;
echo "</p>";*/
}
echo "<p id='errors'>";
echo $errors;
echo "</p>";
}
This doesn't work though. Basically this is what I want to do: If no email address was entered or if it was entered incorrectly, set a variable called $email_error to be true. Then check for that variable, and if it's true, then remove the $phoneError part of the $errors variable.
Man I hope I'm making some sense here. Does anyone know why this doesn't work? It reports all errors if all fields are left empty :(
Thanks!
Amit
You need at first to build up an array of errors, i.e.:
$errors = array();
if (!$phone) { // add more validation as required
$errors['phone'] = $phoneError;
}
if (!$email) {
$errors['email'] = 'No email provided';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Invalid email provided';
}
Then you send, or display the errors:
if (!isset($errors['phone']) || !isset($errors['email'])) {
// send mail here, only if either the phone or the email error is missing
} else {
// display errors
echo '<p id="errors">';
foreach ($errors as $error) {
echo $error;
}
echo '</p>';
}
so...
$sent=false;
if(!$name){
$errors[]='No Name was supplied.';
return($errors);
}
if($phone && validatePhone($phone)){
//send the phone message however...
$sent=true;
}
if($email && validateEmail($email)){
//send the email here...
$sent=true;
}
if(!$sent){
$errors[]='Neither an email or a phone was supplied';
return($errors);
}
classed:
class Communication {
var $sent=false;
var $errors=false;
public function __construct(){
$this->phone=$_POST['phone'];
$this->email=$_POST['email'];
$this->name=$_POST['name'];
if($this->validateName()){
$this->validateEmail();
$this->validatePhone();
}
}
public function validateEmail(){
//do your regex here and eval either false or true to $status
if(!$status){
$this->errors['ErrorInvalidEmail']=ErrorInvalidEmail;
}else{
$this->sendEmail();
}
}
public function validatePhone(){
//do your regex here and eval either false or true to $status
if(!$status){
$this->errors['ErrorInvalidPhone']=ErrorInvalidPhone;
}else{
$this->sendText();
}
}
public function validateName(){
//do your regex here and eval either false or true to $status
if(!$status){
$this->errors['ErrorInvalidName']=ErrorInvalidName;
return(false);
}else{
return(true);
}
}
public function sendEmail(){
$this->sent=true;
//do your sending by email HERE
}
public function sendText(){
$this->sent=true;
// do your sending by text/phone here
}
}
$c=new Communication();
print_r($c->errors);
I believe
if ( !($errors) )
should be
if ( !$errors )
//or
if( !isset( $errors ) )
While there is no benefit over doing it Selsaek's way (above), one way to do it is with a bit mask (a set of constants which are powers of 2, and one storage variable). You OR the storage variable with the constant, and then when you AND the two together later, a nonzero result means the flag was tripped. No reason you can't use an array to store the flag and the text:
$WARNING_MASK = array('name' => 1, 'email' => 2, 'phone' => 4);
$warningflag = 0;
to set a flag an error (you OR the storage variable with a constant):
$warningflag = $warningflag | $WARNING_MASK['name'];
to test for an error (you AND the storage value with the constant):
if ($warningflag & $WARNING_MASK['name']) {}

PHP contact form, am I doing it wrong?

I'm learning PHP and I'm trying to write a simple email script. I have a function (checkEmpty) to check if all the forms are filled in and if the email adress is valid (isEmailValid). I'm not sure how to return true checkEmpty funciton. Here's my code:
When the submit button is clicked:
if (isset($_POST['submit'])) {
//INSERT FORM VALUES INTO AN ARRAY
$field = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($field);
checkEmpty($name, $email, $message);
function checkEmpty($name, $email, $message) {
global $name_error;
global $mail_error;
global $message_error;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$name_error = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$mail_error = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$mail_error = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$message_error = "<span class='error_text'>* Please enter your message</span>";
}
}
// This function tests whether the email address is valid
function isValidEmail($email){
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (eregi($pattern, $email))
{
return true;
} else
{
return false;
}
}
I know I shouldn't be using globals in the function, I don't know an alternative. The error messages are display beside each form element.
First of all, using global is a sin. You are polluting global namespace, and this is bad idea, except little ad-hoc scripts and legacy code.
Second, you are misusing isset - for two reasons:
a ) in given context you pass variable $name to function, so it is always set
b ) empty checks whether variable is set or not
Third, you should separate validation from generating html.
Fourth, you can use filter_var instead of regular expression to test if mail is valid.
Last, your code could look like that:
<?php
if (isset($_POST['submit'])) {
$fields = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($fields);
$errors = validateFields($name, $email, $message);
if (!empty($errors)){
# error
foreach ($errors as $error){
print "<p class='error'>$error</p>";
}
} else {
# all ok, do your stuff
} // if
} // if
function validateFields($name, $email, $post){
$errors = array();
if (empty($name)){$errors[] = "Name can't be empty";}
if (empty($email)){$errors[] = "Email can't be empty";}
if (empty($post)){$errors[] = "Post can't be empty";}
if (!empty($email) && !filter_var($email,FILTER_VALIDATE_EMAIL)){$errors[] = "Invalid email";}
if (!empty($post) && strlen($post)<10){$errors[] = "Post too short (minimum 10 characters)";}
# and so on...
return $errors;
}
First of all, you should really re-think your logic as to avoid global variables.
Eitherway, create a variable $success and set it to true in the top of your functions. If any if statement fails, set it to false. Then return $success in the bottom of your function. Example:
function checkExample($txt) {
$success = true;
if (isset($txt) === true && empty($txt) === true) {
$error = "<span class='error_text'>* Please enter your example text</span>";
$success = false;
}
return $success;
}
I'm not sure this is what you want, the way I see it, you want $mail_error, $message_error and $name_error to be accessible from outside the function. If that's the case, what you need is something like this:
function checkEmpty($name, $email, $message) {
$results = false;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$results['name_error'] = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$results['mail_error'] = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$results['mail_error'] = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$results['message_error'] = "<span class='error_text'>* Please enter your message</span>";
}
return $results;
}
$errors = checkEmpty($name, $email, $message);
now you can test for errors
if($errors){
extract ($errors); // or simply extract variables from array to be used next to form inputs
} else {
// there are no errors, do other thing if needed...
}

Categories