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']) {}
Related
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
}
}
}
My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.
I was having trouble trying to make this function work for ages. Before, I was doing
if ( !filter_has_var(INPUT_POST, 'email') ) {
code here etc.
}
and this never worked though is the correct format for how the function should be set up. reference
Then after playing about with it trying to make it function, i changed 'email' to '$email' and this did the trick. So, now I'm confused, is this a glitch or is my code at the top incorrect?
You can use:
if (isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//Your Code here for valid email...
}
else
{
//Your Code here for invalid email...
}
Through this example i think you can better understand
if ( !filter_has_var(INPUT_GET, 'email') ) {
echo "Email Not Found";
} else {
echo "Email Found";
}
Output
localhost/nanhe/test.php?email=1 //Email Found
localhost/nanhe/test.php?email //Email Found
http://localhost/nanhe/test.php //Email Not Found
Consider on second example
http://localhost/nanhe/test.php
$_GET['email']="info#nanhe.in";
if ( !filter_has_var(INPUT_GET, 'email') ) {
echo "Email Not Found";
} else {
echo "Email Found";
}
But output will be Email Not Found
I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />
Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)
instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error
You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {
For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');
How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.
Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}
function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}
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...
}