I am using an "If..elseif..else" statement. Email validation - php

Hi :) This is my first time posting on here but I can't figure it out and it should be simple. I think I have just been looking at it for too long. So I have a form for which I am carrying out form validation, all the validation works and it sends to the database.
The small issue I have is when it comes to the email and confirm email validation, the first if statement checks if the textbox is empty and if it is I should get the "Email is required" message. But due to the second if statement, I think the $emailErr variable gets overwritten by the second error message which should appear only if the email syntax is invalid.
Therefore, if i leave the textbox empty, i still get the "syntax invalid" message rather than the "email is required" message.
My confusion comes from the fact that, for example, my "firstname" validation (and all other validation) is pretty much the same idea but they do not get overwritten by the second error message which is also presented by using a second if statement.
I will copy the code for my firstname validation and the code for my email validation so you can get an idea of what I am talking about. Any help would be greatly appreciated. If not, im sure ill figure it out eventually :) Thanks!
FIRST NAME VALIDATION - if I leave the textbox blank I get error message "First name is required" - which is correct.
//Check if the firstname textbox is empty
if (empty($_POST['fname']))
//Show error message
{
$fnameErr = "First name is required";
}
//Check if fname is set
elseif (isset($_POST['fname']))
//Check the text using the test_input function and assign it to $fname
{$fname = test_input($_POST['fname']);}
//Check if first name contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
//Show error message & unset the fname variable
{
$fnameErr = "Only letters and white space allowed";
unset($_POST['fname']);
}
else
//Check the text using the test_input function and assign it to $fname
{$fname = test_input($_POST['fname']);}
EMAIL VALIDATION - if I leave the textbox empty I get the error message "Invalid Email Format" - it should be "Email is required" - why is this?
//Check if the email textbox is empty
if (empty($_POST['email']))
//Show error message
{
$emailErr = "Email is required";
}
//Check if email is set
elseif (isset($_POST['email']))
//Check the text using the test_input function and assign it to $email
{$email = test_input($_POST['email']);}
//Check if e-mail syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
//Show error message & unset the email variable
{
$emailErr = "Invalid email format";
unset($_POST['email']);
}
else
//Check the text using the test_input function
{$email = test_input($_POST['email']);}

The proper way to validate an email is by using filter_var
$email = filter_var(filter_var($_POST['email'],FILTER_SANITIZE_EMAIL),FILTER_VALIDATE_EMAIL)
if(!$email)
$invalidemailMessage = 'You have entered an invalid email address!';
End of story.
If you really,really,really need to output "Email required":
if($_POST['email'] == "" || preg_match('/^\s+$/', $_POST['email']) == true) {
$invalidemailMessage = 'Email required.';
} else {
$email = filter_var(filter_var($_POST['email'],FILTER_SANITIZE_EMAIL),FILTER_VALIDATE_EMAIL)
if(!$email)
$invalidemailMessage = 'You have entered an invalid email address!';
}

with some adjustment to your current code you can keep it, ALTHOUGH what #tftd said is absolutely correct with regard to Sanitisation and Validation.
$error = array();
if (empty($_POST['email'])) {
$error[__LINE__] = "Email is required";
} elseif (isset($_POST['email'])) {
$email = test_input($_POST['email']);
}
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$error[__LINE__] = "Invalid email format";
unset($_POST['email']);
} else {
$email = test_input($_POST['email']);
}
if ($error){
print_r($error);
}

Part of your problem with your code is your last if is still being ran so you will always get the error if the email field is empty.
Change this
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
To this
if (isset($email) && !preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))

Related

checking if email and confirm email fields are the same using php

I would like to confirm that the email field and confirm email field match each other in my html form before submitting the form to the database, i have done the following but it doesn't seem to work:
<?php
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'][] = "Invalid email address";
}
if ($_POST['email'] != $_POST['confirmemail']) {
$_SESSION['error'][] = "Email addresses do not match";
}
else {
this is followed by the script to submit the form to the database which works fine. Any suggestions would be welcome, many thanks
There might be whitespace issue causing your comparison to fail. try trimming your inputs before comparison.
$email = trim( $_POST['email'] );
$confirmEmail = trim( $_POST['confirmemail'] );
if ($emsil != $confirmEmail ) {
$_SESSION['error'][] = "Email addresses do not match";
}

PHP Form sends Email even if Email and Name are invalid

Hi everyone and thanks for your time!
Although it's the first time that I try PHP, I've been making a PHP Form and so far I've been able to make it validate the fields, and also that the form doesn't send anything if the fields are empty.
Now... The fields "Name" and "Email" have validation filters...
"Name" doesn't allow more than "letters and white spaces" and "Email" doesn't allow an "invalid Email format".
Example:
Name: Rob3rt... it has a number
Email: anything... isn't an Email address
Subject and Message have no validation filters...
The problem is, that if I fill up all fields, the form sends the Email, even if the information written on "Name" and "Email" doesn't agree with their validation filters...
Q: How can I hold the form from sending an Email, until all fields have the correct information inside?
Here's the code:
// This is the validation code //
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $subjectErr = "";
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "<h5>Name is required</h5>";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "<h5>Only letters and white space allowed</h5>";
}
}
if (empty($_POST["email"])) {
$emailErr = "<h5>Email is required</h5>";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "<h5>Invalid email format</h5>";
}
}
if (empty($_POST["comment"])) {
$commentErr = "<h5>Message is required</h5>";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["subject"])) {
$subjectErr = "<h5>Subject is required</h5>";
} else {
$subject = test_input($_POST["subject"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form>
Form comes here
</form>
// This is the sending code... I think the problem is here... //
<?php
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
$to = "myemail#whatever.com";
$email = "From: " . $email . "\r\n";
$subject = "" . $subject . "\r\n";
$comment = "" . $comment . "\r\n";
mail($to,$subject,$comment,$email);
echo "good";
}
else {
"bad";
}
?>
It is not working, because you never check if an error occurred, you are only checking if the fields are not empty before you send the mail.
The simplest way to fix it is replacing
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
with
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $nameErr === '' && $emailErr === '' && $commentErr === '' && $subjectErr === '') {
There is no no need to check for empty fields again, you have already done it before, so you just need to check if you are POSTing the form and if all errors are empty.
Some advice on how to generally improve your code:
1) Do not handle the HTTP POST in two positions (once above the form and once below). Merge it together in one PHP code block.
2) At least make sure that the user can't re-submit a successful form by reloading the site. After a successful submit, redirect the page. Something like this:
mail($to,$subject,$comment,$email);
header('Location:' . $_SERVER['REQUEST_URI'] . '?status=ok');
exit();
3) separate your HTML from your PHP or you will end up with a huge file which gets hard to maintain. Put your HTML form in a separate file and include it.
Although imho the nicest solution for a form is to sanitize in in JavaScript, submit it via AJAX (with angular, react, jQuery, whatever), handle it (and sanitize the data again) in PHP, send a 4xx HTTP header on error and return the error messages as a JSON object, which you then use in JavaScript.

How to prevent a script from running when email does not pass filter_var

I'm trying to make the emails pass validation by using filter_var. However, I am not sure how to prevent the script from processing the form data to my database if the email is not valid.
I have
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
exit();
}
the email obviously comes from what was entered in by the user and is in the $_POST variable. The script DOES show the email as valid or invalid, however it STILL processes the script and places the form data into my database. I thought that putting "exit()" would be the solution to this, or the proper way to handle when it's not valid. It simply opens a new page where the echo print shows.
What am I missing or doing wrong? Ideally I would like the form field to highlight and give the user some indication that they've entered in an incorrectly formatted email address (although I know that is a different topic and somewhat a bells and whistles type of thing), but I certainly do not want to allow the script to process the data into my database.
The answer lies in where the validation code was placed. Instead of placing it RIGHT AFTER the posted variables and before the SQL insertion code, I put it at the very end of the script. So the posted data went into the database before they can be validated.
So now, I have (which works)
$name = $_POST['name'];
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is not a valid email address");
exit();
} else {
$msg_to_user = '<br /><br /><h4>Thanks ' . $name . ', we will send you news when appropriate. Take care!</font></h4>';
$name = "";
$email = "";
}
// THE SQL SELECT STATEMENT TO ENSURE NO DUPLICATE EMAIL AND THEN THE INSERT STATEMENT TO PUT THE DATA IN THE DATABASE COMES AFTER THE CODE ABOVE

Validating contact number in php form

I'm trying to validate a contact number in this form (555)555-5555
but it won't work I don't know what is the problem. If I leave it blank it will print the line
"Please fill out your contact number." but if I enter any number not in the specified from. It won't print the error line. Can some one tell me what is the problem?
Thank you.
if (!preg_match( "/^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/",($_POST['pcnumber'])) && (!empty($_POST['pcnumber']) ))
{
$msg = "pcnumber: $_POST[pcnumber] ";
}
else
{
$pcnumber = NULL;
echo "Please fill out your contact number.";
}

See if # symbol is in field and proceed with form validation

I am trying to set up a web form for my website and I want to search the user's input for an # symbol and if it is not there, the form should not validate and a message should show up asking the user to recomplete the form.
Here's what I have so far:-
$at = "#";
if (is_null($at[$email]))
{
return FALSE;
}
I hope someone can help me!
<?php
$email = "someone#example.com";
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
echo "Valid email address.";
}
else {
echo "Invalid email address.";
}
?>
Or little bit more modern:
<?php
$email_address = "someone#example.com";
if (preg_match("/^[^#]*#[^#]*\.[^#]*$/", $email_address)) {
return "E-mail address";
}
?>

Categories