Check valid domains in an eMail address - php

I have the following function that checks whether an eMail is valid:
function validate_email ($getemail, $type)
{
$email = $getemail;
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$chkdomain = explode("#", $email);
$domain = $chkdomain[1];
switch ($type) :
case 1: //FOR USERS
if ($domain == "oxfordmontessori.com" || $domain == "student.com" || $domain == "vendor.com")
return 'Not Valid';
else
return TRUE;
endswitch
;
} else {
return FALSE;
}
}
I am calling function in this way.
var_dump($email);
$response = validate_email($email, '1');
var_dump($response);
if ($response == FALSE) {
$error = "Incorrect Email-Id";
} elseif ($response == 'Not Valid') {
$error = "Email domain is not valid for user.";
}
var_dump($response);
The code has the following issues
Function is that not much restrict with email validation like sunrise#o.com and 'sunrise#o.c' both are consider as valid email id's.
If function return TRUE than also I get "Email domain is not valid for user."
One issue is still their that is on return of TRUE it gives me error Email domain is not valid for user.

its not working because if the domain is set to oxfordmontessori.com student.com or vendor.com, it returns "Not Valid", so #a.com and #b.com will return true. Unless your system is designed to stop people from using those specific domains.
You should probably have either an external variable to store the error, or a pointer in the arguments, rather than returning multiple data types from the function. Either a true or false, maybe an integer, but not a mix of true, false, and string. I think strings (when checked against boolean operators) return true every time.

you can also use html5 email inputs for validation.
Validation is mostly done by regex functions like
preg_match()
Here is an example of using regular expressions for validating email addresses

Related

How do i validate a company email using php preg_match function [duplicate]

I am trying to code a registration form where I am validating the email used to sign up.
In a nutshell, I want to ensure that the email ID used to register, is a company domain, and not something like gmail or yahoo.
I have the following code to check IF an email is a part of the given domain, how can I modify this to check that it ISNT in a given list of domains? (eg : gmail.com, yahoo.com,hotmail.com, etc).
return (bool) preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $domain);
Im thinking it should be along these lines, but not entirely sure :
function validate($email)
{
$error = 0;
$domains = array('gmail.com','yahoo.com','hotmail.com');
foreach($domains as $key=>$value)
{
if(preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $value)
{
$error=1;
}
}
if($error==0)
return true;
else
return false;
EDIT : I tried all the answers given here, the form still submits without a problem no matter what domain I use! (Even a non email seems to work!)
This is how I'm calling the function -
if(isset($_POST['clients_register']))
{
//Must contain only letters and numbers
if(!preg_match('/^[a-zA-Z0-9]$/', $_POST['name']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 8-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,15}$/', $_POST['password']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (validateEmail($_POST['email'])==false)
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
//Syntax for SQL Insert into table and Redirect user to confirmation page
}
}
Problem is, no matter what I do, the user gets redirected to the confirmation page (Even with a name made of numbers and an email like "table".
You should do that in a separate step. First check if the e-mailaddress has a valid syntax. Than extract the domain and see if it's not in your blacklist.
function validate($email)
{
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
$domains = array('gmail.com','yahoo.com','hotmail.com');
list(, $email_domain) = explode('#', $email, 2);
return !in_array($email_domain, $domains);
}
function validateEmail($email)
{
// Etc, just an array of the blacklisted domains
$blacklistDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'googlemail.com'];
// Check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Split the email after the '#' to get the domain
$emailParts = explode('#', $email);
if (in_array(end($emailParts), $blacklistDomains)) {
return false;
}
return true;
}
You'll need a pretty big list of domains.
PHP
// Suposing that $email is a valid email
function validate($email) {
$invalidDomains = array('gmail.com','yahoo.com','hotmail.com');
$parts = explode('#',$email);
$domain = $parts[1];
if(!in_array($domain,$invalidDomains)) return true;
return false;
}
Let me know if it's useful.

How do I validate an e-mail address so that it must have a .edu ending domain name only?

I am looking to validate e-mail addresses, only allowing e-mails ending with with an #ucla.edu
This is my current function.
Code:
function validate_email($email)
{
if (strlen($email) < 4 || strlen($email) > 64)
return 1;
elseif (!preg_match("/^([a-z0-9_\-]+)(\.[a-z0-9_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/i",
$email))
return 2;
else
return 0;
}
// End function
One option if you are going to end up writing a lot of validation is to use an existing library to handle the bulk of the work for you. A good one to use is:
https://github.com/Respect/Validation
for example with this you could write:
use Respect\Validation\Validator;
$eduEmailValidator = Validator::email()->endsWith(".edu");
$eduEmailValidator->validate('waaah'); // false
$eduEmailValidator->validate('waaah#domain.com'); // false
$eduEmailValidator->validate('waaah#domain.edu'); // true
This leads to some easy to read code which you'll really appreciate when you come back to this in a few month's time!!
function validate_email($email)
{
return preg_match('/.+#ucla.edu$/i',$email); //true if success
}
<?php
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
exit("Invalid email address");
if(substr($email, -4) !== '.edu')
exit("Invalid email provider");
It's not the perfect solution, but it'll do what you want it to.
Obviously, change the exit() calls to whatever handling you have
You can use substring in your case. Use the below code to validate email based on #ulca.edu:
function validate_email($email)
{
$pattern = "#ulca.edu";
$validate = substr($email, -9);
if($pattern == $validate )
{
//your code to allow email
}
else
{
//dont allow
}
}

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

Domain specific email validation

I am trying to code a registration form where I am validating the email used to sign up.
In a nutshell, I want to ensure that the email ID used to register, is a company domain, and not something like gmail or yahoo.
I have the following code to check IF an email is a part of the given domain, how can I modify this to check that it ISNT in a given list of domains? (eg : gmail.com, yahoo.com,hotmail.com, etc).
return (bool) preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $domain);
Im thinking it should be along these lines, but not entirely sure :
function validate($email)
{
$error = 0;
$domains = array('gmail.com','yahoo.com','hotmail.com');
foreach($domains as $key=>$value)
{
if(preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $value)
{
$error=1;
}
}
if($error==0)
return true;
else
return false;
EDIT : I tried all the answers given here, the form still submits without a problem no matter what domain I use! (Even a non email seems to work!)
This is how I'm calling the function -
if(isset($_POST['clients_register']))
{
//Must contain only letters and numbers
if(!preg_match('/^[a-zA-Z0-9]$/', $_POST['name']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 8-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,15}$/', $_POST['password']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (validateEmail($_POST['email'])==false)
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
//Syntax for SQL Insert into table and Redirect user to confirmation page
}
}
Problem is, no matter what I do, the user gets redirected to the confirmation page (Even with a name made of numbers and an email like "table".
You should do that in a separate step. First check if the e-mailaddress has a valid syntax. Than extract the domain and see if it's not in your blacklist.
function validate($email)
{
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
$domains = array('gmail.com','yahoo.com','hotmail.com');
list(, $email_domain) = explode('#', $email, 2);
return !in_array($email_domain, $domains);
}
function validateEmail($email)
{
// Etc, just an array of the blacklisted domains
$blacklistDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'googlemail.com'];
// Check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Split the email after the '#' to get the domain
$emailParts = explode('#', $email);
if (in_array(end($emailParts), $blacklistDomains)) {
return false;
}
return true;
}
You'll need a pretty big list of domains.
PHP
// Suposing that $email is a valid email
function validate($email) {
$invalidDomains = array('gmail.com','yahoo.com','hotmail.com');
$parts = explode('#',$email);
$domain = $parts[1];
if(!in_array($domain,$invalidDomains)) return true;
return false;
}
Let me know if it's useful.

IP Address Validation Help

I am using this IP Validation Function that I came across while browsing, it has been working well until today i ran into a problem.
For some reason the function won't validate this IP as valid: 203.81.192.26
I'm not too great with regular expressions, so would appreciate any help on what could be wrong.
If you have another function, I would appreciate if you could post that for me.
The code for the function is below:
public static function validateIpAddress($ip_addr)
{
global $errors;
$preg = '#^(?:(?: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]?)$#';
if(preg_match($preg, $ip_addr))
{
//now all the intger values are separated
$parts = explode(".", $ip_addr);
//now we need to check each part can range from 0-255
foreach($parts as $ip_parts)
{
if(intval($ip_parts) > 255 || intval($ip_parts) < 0)
{
$errors[] = "ip address is not valid.";
return false;
}
return true;
}
return true;
} else {
$errors[] = "please double check the ip address.";
return false;
}
}
I prefer a simplistic approach described here. This should be considered valid for security purposes. Although make sure you get it from $_SERVER['REMOTE_ADDR'], any other http header can be spoofed.
function validateIpAddress($ip){
return long2ip(ip2long($ip)))==$ip;
}
There is already something built-in to do this : http://fr.php.net/manual/en/filter.examples.validation.php See example 2
<?php
if (filter_var($ip, FILTER_VALIDATE_IP)) {
// Valid
} else {
// Invalid
}
Have you tried using built-in functions to try and validate the address? For example, you can use ip2long and long2ip to convert the human-readable dotted IP address into the number it represents, then back. If the strings are identical, the IP is valid.
There's also the filter extension, which has an IP validation option. filter is included by default in PHP 5.2 and better.
Well, why are you doing both regex and int comparisons? You are "double" checking the address. Also, your second check is not valid, as it will always return true if the first octet is valid (you have a return true inside of the foreach loop).
You could do:
$parts = explode('.', $ip_addr);
if (count($parts) == 4) {
foreach ($parts as $part) {
if ($part > 255 || $part < 0) {
//error
}
}
return true;
} else {
return false;
}
But as others have suggested, ip2long/long2ip may suit your needs better...

Categories