email validation form submitting despite errors - php

I have some if statements validating email addresses submitted to my form below. However the form submits even though not all the if conditions below are met. The one it seems to respect is the filter_var condition. Why would it do this? the validation that is failing is the last if statement saying the email is unreachable. on the form it says the email address is unreachable. but it submits the form by email anyways. $scrubbed is a function I use in my form to clean the form fields from possible spam
if (isset($scrubbed["email"])) {
if (strlen($scrubbed["email"]) > 254) {
echo "<p>The email address is too long: it must be 254 or less.</p>";
}
// Validate syntax with PHP.
if ((($email = filter_var($scrubbed["email"], FILTER_VALIDATE_EMAIL)) === false)) {
echo "<p>The email address has an invalid syntax.</p>";
}
// Validate DNS reachability.
$host = substr($email, strrpos($email, "#") + 1) . ".";
if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
echo "<p>The email address is unreachable.</p>";
}
}

It would be nice if you accept the answers to your questions.
$scrubbed["email"] is simply empty and therefor the email is always invalid.
Let's create a simple form that will be submitted to us.
<!doctype html>
<html>
<head>
<title>Form</title>
</head>
<body>
<?php
/**
* Validate submitted email address.
*
* #return null|string
* Returns <code>NULL</code> if the email address is valid, if the
* email address is invalid a string explaining the problem is returned.
*/
function validate_email() {
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email === false) {
return "The email address has an invalid syntax.";
}
if (strlen($email) > 254) {
return "The email address is too long: it must be 254 or less.";
}
$host = substr($email, strrpos($email, "#") + 1) . ".";
if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
return "The email address is unreachable.";
}
}
// Check if we were called via POST.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate the email address and display the error message (if any).
if (($error = validate_email())) {
echo "<p>{$error}</p>";
}
// Otherwise let the user know that everything is okay.
else {
echo "<p>The email address is valid, not too long, and reachable.</p>";
}
}
?>
<form action="/" method="post" accept-charset="utf-8">
<input type="email" name="email">
<input type="submit">
</form>
</body>
</html>
Please note that this is only some code for illustration purposes and has nothing to do with proper software design, re-usability, … well anything that is part of good software.

Related

Form Email Validation in backend PHP

I am using a form to get newsletter sign ups on my website. I am using a contact.php file which works well but there is no validation so I occasionaly and sometimes frequently get blank responses.
I'm not sure why this is, but I believe I need validation.
This is my original code
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
and this is the code I tried to add to validate but it doesnt work.
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "jcash1#gmail.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
/* Validation */
$error=0; // check up variable
$errormsg = '<ul class="errorlist">';
/* get it checking */
if(!check_email($email))
{
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
}
$errormsg .= '</ul>';
if($error == 0) {
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo 'error|'. $errormsg;
}
?>
Can anyone offer some insight?
I cannot for the life of me get this to work...
I am getting an Error with the plugin and I have loaded it correctly
so I tried adding this :
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
like so:
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo("$email is not a valid email address");
}
?>
Which is not working. I think it is beauce I have implemented the code in the wrong place but I am not sure. Any help would be greatly appreciated.
You can use filter_var() function in PHP for validating email addresses.
For simply validating email addresses in PHP you can use it like this,
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}
And your code can be improved like this.
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
}
else {
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
echo '</ul> error|'. $errormsg;
}
If you want to know more about it, visit official PHP documentation page here : http://php.net/manual/en/filter.filters.validate.php
Or use jquery validation plugin. I highly recommend it.
Code will look similar to below
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
You can use server side validation by using this code
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} 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

PHP form validation that includes SUBMIT button

I have been trying to find a way to validate email in my PHP code. I can only give you parts of my code cause it is really long. What I want to do is to have a person enter their email address by clicking a submit button and if they have entered their email in an unacceptable format, an error message appears. But my problem is: how can I COMBINE a tag WITH "function validate email($field)"? In other words, I know how to combine (PART A) and (PART B), that is easy enough. But what I really want to do is combine (PART B) with (PART C) and not use (PART A) at all. Is that possible? Can I somehow include "isset" inside "function validate email($field)"? I must have a submit button and I must be able to validate the email.
(PART A) <?php //formtest2.php
if (isset($_POST['email'])) $email = $_POST['email'];
else $email = "(Not entered)";
?>
(PART B) <?php
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
?>
(PART C) <body>
Your email is: $email<br>
<form method="post" action="brownuniversity.php">
What is your email address?
<input type="text" name="email">
<input type="submit">
</form>
</body>
Hi first of all your gonna want to change this whole thing,
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
To this little bit.
function validate_email( $field ){
if (preg_match("/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $field)){
return true;
}
return false;
}
You'll have to do the error messages elsewhere, but this is more portable. ( and I give you a much better Regx for emails ), now you can just do this
if(isset($_POST['email'])){
$email = trim( $_POST['email'] ); //remove any whitespaces from pasting email.
if(validate_email($email)){
//send mail or whatever
}else{
//show errors
}
}
You will still have to check if isset( $_POST['email'] inside the validation isn't really the place to check for it, it should only be concerned with if the data is valid or not, not if there is no data. Also you'll need to check that the form was posted anyway before calling the function and the isset serves both these needs. I updated the answer, you don't really need a validation message on the case that it is not set, because if that is the case they didnt submit the form, it should always be set on form submission.

PHP email validation with filter_var() and preg_match()

I am trying to build a form with good email validation, I am trying to use filter_var() combined with preg_match(), but with my if statement below it isn't working. Only one of the conditions is being met it seems. How else could I write this so that it works?
$email = (isset($scrubbed['email']))
? filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL, FILTER_SANITIZE_EMAIL)
: NULL
;
if ((!$email) && (!preg_match("/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/", $email))) {
echo 'Invalid Email Address, please correct errors';
} else {
$email = strip_tags($scrubbed['email']);
}
What's the purpose of validating the email address again? PHP's filter_var() already allows all kinds of email variations and you'll possibly never create a regular expression that's even close to the one they use.
The email validation I use looks like the following (applied to your code):
<?php
if (isset($scrubbed["email"])) {
// #see http://stackoverflow.com/a/574698/1251219
if (strlen($scrubbed["email"]) > 254) {
echo "The email address is too long: it must be 254 or less.";
}
// Validate syntax with PHP.
if (($email = filter_var($scrubbed["email"], FILTER_VALIDATE_EMAIL)) === false) {
echo "The email address has an invalid syntax.";
}
// Validate DNS reachability.
$host = substr($email, strrpos($email, "#") + 1) . ".";
if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
echo "The email address is unreachable.";
}
}
?>
Ever wondered what PHP's regular expression looks like?
/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}#)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD
More info can be found at Comparing E-mail Address Validating Regular Expressions.
if ((!$email) && (!preg_match("/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/", $email)))
should be
if ((!$email) || (!preg_match("/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/", $email)))
...

PHP: Check does email contains "#" and "."

Im new in php and this should be a easy to make, but I dont now how.
I want to check does $address has characters "#" and "."
<?php
function testEmail($address){
$a = strpos("/#/", $address);
$b = strpos("/./", $address);
if (($a != false) && ($b != false)) {
echo "Email is OK";
} else {
echo "Email is NOT OK";
}
}
testEmail("testmail#gmail.com");
?>
You can simply use filter_var to check validity of email.
$email = 'gaurang#gmail.com'
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Email correct
}
else {
//Email not correct
}
Is your question about this specific piece of code? Then #wroniasty's answer is correct.
But you really don't want to use a regex to test email validity, unless you want to use monstrosities like these.
However, if your question really is "How can I validate an email address?", then take a look at filter_var().
You can pass it the filter FILTER_VALIDATE_EMAIL, so it will validate the email address catching quite a bit of edge cases.
You can check an address using the following code:
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// valid email
} else {
// invalid email
}
<?php
function testEmail($address) {
if (preg_match ( "/\.|#/", $address))
echo "Email OK";
else
echo "Email not OK";
}
?>
a better way to check for valid email address:
<?
function isValidEmail($email){
return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);
}
?>

Categories