This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What is the best regular expression for validating email addresses?
Is there a php library for email address validation?
On my register form a user will add his email and then get an email to verify his account. However I want to have a simple email validation and I would like to know if the following is appropriate.
<?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.";
}
?>
Try:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Valid';
} else {
echo 'Invalid';
}
Your regular expression unnecessarily forbids subdomains, such as user#unit.company.com. Additionally, you shouldn't use the deprecated eregi.
Instead of reinventing your own wheel, use filter_var:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
Apart from a regex, you can also use filter_var:
if (filter_var('someone#example.com', FILTER_VALIDATE_EMAIL)) === false)
{
echo "Invalid email address.";
}
Email validation is a bit tricky, because the RFC that specifies the format of email addresses is way more unrestrictive that people think. For example, the following are all valid email addresses:
"Abc#def"#example.com
"Fred Bloggs"#example.com
"Joe\Blow"#example.com
"Abc#def"#example.com
customer/department=shipping#example.com
$A12345#example.com
!def!xyz%abc#example.com
_somename#example.com
The correct regex for email validation seems to look something like this, which I won't even try to look into ;) However, when using PHP, you should really use filter_var(), like so:
$valid = filter_var($email, FILTER_VALIDATE_EMAIL);
# $valid will be TRUE if the email address was valid,
# otherwise FALSE.
RFC822 seems to contain the original email format specification, but I think that 2822 (as linked above) is just a revision / amendment of that original RFC.
Related
Unfortunately I could not find the answer in other questions even though some of them seems to be similar. I am new to phpmailer but I managed to succesfully send email succesfully through smtp by using below code. However, I wish to stop sending emails with empty fields but I can't find proper sintax to do it and I would appreciate advise as how to stop email being sent if fields are empty or how to make fields required . (I know how to make client side validation but server side is a problem). Please see below:
<?php
if(isset($_POST['submit'])) {
$message=
'Name: '.$_POST['name'].'<br />
Subject: '.$_POST['subject'].'<br />
Email: '.$_POST['email'].'<br />
Message: '.$_POST['message'].'';
require "PHPMailer-master/class.phpmailer.php";
$mail = new PHPMailer();
require "smtp.php";
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->Subject = "Message from www";
$mail->MsgHTML($message);
$mail->AddAddress("address1#domain.com", " First receipient");
$mail->AddCC("address2#domain.com", "Second receipient");
$result = $mail->Send();
$message = $result ? '<div class="alert alert-success" role="alert"> Message has been sent ! </div>': '<div class="alert alert-danger" role="alert"><strong>Error!</strong> !</div>';
unset($mail);
}
?>
You just need to tack on some checks into your if statement. empty() is great for checking for empty, null, or 0 fields
if(isset($_POST['submit'])
&& !empty($_POST['name'])
&& !empty($_POST['subject'])
&& !empty($_POST['email'])
&& !empty($_POST['message'])) {
You can do some validation before your if statement to make sure the fields are filled and valid, and throw an error if they aren't.
Follow what #anyber has suggested, I just wanted to follow up and let you know that based on your code, this looks like a contact us form.
You don't want to set the from to the email that's entered on the form, you should change that to your email address. Setting the from with someone else's email can lead to a lot of problems, if that user has DMARC or other authentication methods enabled, take a look at this resource: Common Contact US Problems
How do I validate the first name to only contain a-z characters using php. I have the following at the moment:
if (empty($myFirstName)) {
echo "<p>Please enter your first name!</p>";
else if(!preg_match("/^[a-zA-Z]$/", $myFirstName)){
echo "Your first name can only contain letters!";
}
Here's a working code :
if (empty($myFirstName)) {
echo "<p>Please enter your first name!</p>";}
else if(preg_match("/[^a-zA-Z]/", $myFirstName)){
echo "Your first name can only contain letters!";
}
I did a little modification to the regex : I added a ^ in the group, and removed the anchors.
As a result, your regex will match any character which is not a letter, and display the error message if there is a match.
I strongly advice you to validate user input at least on server side, and on client side if you want to.
For an email validation, the html filter works on client side.
On server side, you can use pre-set PHP filters :
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "email OK";
}
FYI, there is a regexp matching emails according to the RFC2822 standards :
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
May be you can use
if(! ctype_alpha($myFirstName) )
{
//check for alphabetic inputs only
echo "Your first name can only contain letters!";
}
Php manual
Your if is incorrect.
!preg_match("/^[a-zA-Z]$/", $myFirstName)
will only hold true if $myFirstName is not a single alpha character
to ensure that $myFirstName is not any number of alpha characters, try
!preg_match("/^[a-zA-Z]*$/", $myFirstName)
I'm sure this is a simple question, that you'll be annoyed at and answer with a simple link.
My issue is that I can't find what I'm looking for, because I don't understand enough about PHP/MySQL/HTML forms to come up with a particularly Google-able query.
I want to restrict the character set for an email field in a manner like:
*#*.tld
or
*#domain.tld
if that makes sense?
Thanks in advance,
If you want to check domain in your email you can try with this one
$arr = explode('#', $email_address);
if ($arr[1] == 'domain.tld')
{ // Then it's correct }
Or if you want to validate email address, You can validate your email address after form submission with filter_var() in server side
<?php
$email_a = 'joe#example.com';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.";
}
?>
Have a look here for details:
http://php.net/manual/en/filter.examples.validation.php
I am currently working with AJAX/JS to have form without a button click or page refresh. The inquiry I have is in regards of email validation. Right now the PHP code checks if an email address is valid or not. I would like to only have it accept emails from a certain domain. How can I achieve through php to accept only email address from gmail? Example
PHP for validation of email:
if($_POST) {
$email = $_POST['email'];
if (preg_match('|^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $email)) {
echo ('<div id="email_input"><span id="resultval">'.$email.'</span></div>');
}
else {
echo ('<div id="email_input"><span id="resultval">Include a valid email address.</span></div>');
}
}
Php has an easy function to help you with checking if an email address is valid:
$isValid = filter_var($email, FILTER_VALIDATE_EMAIL);
To check if the email adress is a gmail address, the following would do the trick:
list ($user, $domain) = explode('#', $email);
$isGmail = ($domain == 'gmail.com');
Be careful with your regex, it won't validate all actual email addresses.
You have a built-in PHP function to check if an email is valid :
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
If this returns true, then you just have to check if the string ends with #gmail.com. Note that there may be some strange issues with this function, because email validation standards can be surprising.
If you really want a regex which validates all email addresses, here it is :
(?:[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
You should change you're regular expression to this
'|^[A-Z0-9._%+-]+#gmail\.com$|i'
I have a simple PHP mailer script that takes values from a form submitted via POST and mails them to me:
<?php
$to = "me#example.com";
$name = $_POST['name'];
$message = $_POST['message'];
$email = $_POST['email'];
$body = "Person $name submitted a message: $message";
$subject = "A message has been submitted";
$headers = 'From: ' . $email;
mail($to, $subject, $body, $headers);
header("Location: http://example.com/thanks");
?>
How can I sanitize the input?
Sanitize the post variable with filter_var().
Example here. Like:
echo filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
Since you're not building an SQL query or anything here, the only relevant validation that I can see for those inputs is an email validation for $_POST["email"], and maybe an alphanumeric filter on the other fields if you really want to limit the scope of what the message can contain.
To filter the email address, simply use filter_var:
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
As per Frank Farmer's suggestion, you can also filter out newlines in the email subject:
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
As others have noted, filter_var is great. If it's not available, add this to your toolchest.
The $headers variable is particularly bad security-wise. It can be appended to and cause spoofed headers to be added. This post called Email Injection discusses it pretty well.
filter_var is great, but another way to assure that something is an email address and not something bad is to use an isMail() function. Here's one:
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
So to use this, you could do:
if (isset($_POST['email']) && isEmail($_POST['email'])) {
$email = $_POST['email'] ;
} else {
// you could halt execution here, set $email to a default email address
// display an error, redirect, or some combination here,
}
In terms of manual validation, limiting the length using substr(), running strip_tags() and otherwise limiting what can be put in.
You need to remove any newlines from input provided by users in $headers, which gets passed to mail() ($email in your case)! See Email injection.
PHP should take care of sanitizing $to and $subject, but there are versions of PHP with bugs (Affected are PHP 4 <= 4.4.6 and PHP 5 <= 5.2.1, see MOPB-34-2007).
You can use the code from artlung's answer above to validate email..
I use this kind of code to prevent header injection ..
// define some mail() header's parts and commonly used spam code to filter using preg_match
$match = "/(from\:|to\:|bcc\:|cc\:|content\-type\:|mime\-version\:|subject\:|x\-mailer\:|reply\-to\:|\%0a|\%0b)/i";
// check if any field's value containing the one or more of the code above
if (preg_match($match, $name) || preg_match( $match, $message) || preg_match( $match, $email)) {
// I use ajax, so I call the string below and send it to js file to check whether the email is failed to send or not
echo "failed";
// If you are not using ajax, then you can redirect it with php header function i.e: header("Location: http://example.com/anypage/");
// stop the script before it reach or executing the mail function
die();
}
The mail()'s header filtering above is too strict, since some users may be using the filtered strings in their message without any intention to hijack your email form, so redirect it to a page that is explaining what kind of strings that is not allowed in the form or explain it on your form page.