checking if email and confirm email fields are the same using php - 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";
}

Related

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.

Is this a pointless check?

is checking if the email has been filled out pointless means that I have a function that checks for # & .? Would this slow it down or is there no harm?
Form PHP
$email = $_POST['email'];
if (empty($email)) {
$email_error = "Your email can not be blank!";
} else if (email_filter($email) == false) {
$email_error = "Please enter a valid email address!";
} //Add email check here! (sql query)
Email Function
function email_filter($str) {
if (preg_match('/(?=.*[#.])/', $str)) {
return true;
}
return false;
}
This is not going to slow you down. The extra processing time is negligible compared to all of the other processing which happens when serving a web page.
I like to rely on the language to check just in case something changes or a regular expression is buggy:
Here is a good example from w3schools
<?php
$email = "john.doe#example.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>

How can I give an error if all fields are not filled in?

Basically this is my registration form. I want to make it so if all the fields are not filled in it will give an error. What do I do from here? I would also like to display the error as $msg
<?php
include'db.php';
$msg='';
if (empty($_POST[''])
|| empty($_POST['password'])
|| empty($_POST['repassword'])
|| empty($_POST['user_firstname'])
|| empty($_POST['user_lastname'])
){
// details sent Form
$company=mysql_real_escape_string($_POST['company']);
$address=mysql_real_escape_string($_POST['address']);
$email=mysql_real_escape_string($_POST['email']);
$phone=mysql_real_escape_string($_POST['phone']);
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/'; //this defines what a valid email should be
if(preg_match($regex, $email))
{
$activation=md5($email.time()); // Encrypted email+timestamp, so randomly generated and unique
$count=mysql_query("SELECT uid FROM preciousmetals WHERE email='$email'") or die(mysql_error());
if(mysql_num_rows($count) < 1)
{
mysql_query("INSERT INTO preciousmetals(company,address,email,phone,activation) VALUES('$company','$address','$email','$phone','$activation');");
// sending email
include 'smtp/Send_Mail.php';
$to=$email;
$subject="Email verification";
$body='Hello, we need to make sure you are human. Please verify your email and get started using your Website account. '.$base_url.''.$activation.'';
Mail($to,$subject,$body);
$msg= "Registration successful, please activate email.";
}
else
{
$msg= '<font color="#cc0000">This email is already in use, please enter a different one.</font>';
}
}
else
{
$msg = '<font color="#cc0000">The email you have entered is invalid, please try again. </font>';
}
}
?>
Thank you for helping out!
Simply do
if (empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])){
$msg = 'You have not filled all fiels';
} else {
// details sent Form
......
}
echo $msg;
And also check for filter_var() for email validation its much more nicer than regEx
http://php.net/manual/en/filter.examples.validation.php

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

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

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