PHP Form sends Email even if Email and Name are invalid - php

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.

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";
}

I have 3 fields validating correctly. The submissions post to a text file correctly. However

I have 3 fields validating correctly. The submissions post to a text file correctly. However, they post - - (as I have in the code to separate each section) even when the submit button is clicked without filling in the information. There should not be any empty information with just 2 - - printed to the text file without filling in the 3 fields first. How can I fix that? Sorry for the inconvenience, I answered my own question in another post and was able to fix the problem. Thank you for your time.
Here is my code
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['website'])) {
if(empty($_POST['name'])) {
$errors[] = "Name is required";
} else{
$name = htmlentities($_POST['name']);
$name = test_input($_POST['name']);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors[] = "Only letters and white space allowed for the name";
}
}
if(empty($_POST['email'])) {
$errors[] = "Please provide your Email address.";
} else if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ===
false){
$errors[] = "Your Email is not valid.";
} else {
$email = htmlentities($email);
}
if(empty($_POST['website'])) {
$errors[] = "Please provide your company URL.";
} else{
$website = htmlentities($_POST['website']);
$website = test_input($_POST['website']);
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$errors[] = "Please provide a valid URL for your company.";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$data = $name . " - " . $email . " - " . $website;
$file = "textfile.txt";
if($_POST){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}
?>
In the html I have
<?php
if(empty($errors) === false){
?>
<ul>
<?php
foreach($errors as $error){
echo "<li>",$error,"</li>";
}
?>
</ul>
<?php
}else{
if(isset($name, $email, $website)){
echo "<b>Thank you for your submission.</b>";
}
}
?>
</div>
<div class="wrapper w3-round-xlarge">
<div class="formtitle w3-round-xlarge">Thank you for filling in all fields below
</div>
<div class="formwrapper w3-round-xlarge">
<form name="mobile" id="mobile" method="post" enctype="multipart/form-data" action="data.php"><br/>
etc. (the html document starts and ends correctly. Thank you for your help.
If all three inputs are required them, place required into the html input.
<Input name="email" required />
Do this for each input. This will not allow for the form to be processed until all fields are filed.
Sorry to inconvenience anyone for taking the time to read my post. I was able to fix the problem simply by removing the following from the php code above my html and changing the following
if($_POST){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}
to ...
<?php
}else{
if(isset($name, $email, $website)){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
echo "<b>Your submission has been sent.</b>";
}
and adding it to the html div area

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

PHP email sending issue with validated fields

I am facing an issue, I have successfully validated the input and required fields in my form. But if the user Submits the form, no matter if the fields are empty; it shows the error message with fields but also send the empty email.
I believe there is just a simple tweak that needs to be done. But I am lost. Please look into the below code I have:
<?php
$nameErr = $snameErr = $emailErr = $ownerNameErr = $ownerNatErr = $genderErr = $websiteErr = "";
$name = $sname = $regAddress = $email = $gender = $comment = $ownerName = $ownerNat = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["sname"]))
{$snameErr = "Company Second Name is required";}
else
{
$sname = test_input($_POST["sname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$sname))
{
$snameErr = "Only letters and white space allowed";
}
}
extract($_POST);
$to="example#example.com";
$subject="Subject";
$body="<table width='100%' cellspacing='10' cellpadding='0'>
<tr>
<td style='color:blue;font-weight:bold;margin-left:500px;font-size:20px;' colspan='3'>My Form</td>
</tr>
<tr>
<td>Name</td>
<td>:</td>
<td>$name</td>
</tr>
<tr>
<td>Second Choice</td>
<td>:</td>
<td>$sname</td>
</tr>
</table>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: MySite '."\r\n";
/*$headers .= 'Reply-To:'."$textfield5"."\r\n";*/
if(mail($to,$subject,$body,$headers))
{
$msg = "Thank you for contacting us. We will get back to you soon.";
/*$msg= "Successfully Sent";*/
}
else
{
$msg= "msg not sent";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML Part
<span class="error">* <?php echo $ownerNatErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
input type="submit" name="submit" value="Submit Information">
Any help/Suggestion is highly appreciated.
Regards.
Your validation is correct and I assume it does what you want, however: you do not prevent the mail() function from running if the validation fails.
You could do this:
if ($valid) {
if (mail(...) {
...
} else {
...
}
}
This $valid variable sou should set to true by default and in the if statement, where you set the error messages, you should the variable to false.
This way the mail function would be called if the input is valid only.
Cheers.
You check the parameters for errors and set some error messages but your code calls mail anyway, even if you found an error.
You might want to add some conditions:
if($snameErr === '' && $nameErr === '' ...) {
// call mail here, check whether it was successful and
// tell the user about it
} else {
// show error message or something else
}
By the way, I guess your code is vulnerable because you use extract($_POST). An attacker might inject arbitrary variables and can therefore bypass your checks.

queries regarding PHP mail() 'issues'

So I recently made a basic site for a family members small company. I included a mail form, for enquiries etc.
here is the code i use:
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
?>
now when I try it, it works absoloutely fine. However I have noticed sometimes it is realllllly slow and so we have been receiving blank emails through the form (the user input data is not present), so it appears someone has attempted to use it and given up perhaps because it is taking too long?
I am assuming this is to do with the mail server rather than php mail. But I wanted to see if anyone could highlight potential issues that I could take to the company hosting for her?
many thanks,
check if name and email fields are entered and then proceed with mail function..this reduces getting blank emails.
<?php
if (isset($_POST['name']) && isset($_POST['email'])) //check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Alternatively you can also use array_key_exists()
<?php
if (array_key_exists("name", $_POST) && $_POST["name"] != "" && array_key_exists("email", $_POST) && $_POST["email"] != "")
//check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Actually you are not checking if someone fill the form empty that's why you are getting blank fields
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($data))
{
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
}
?>

Categories