I'm trying to verify the entered email address to be in a specific domain only; for example: only #hotmail.com emails are accepted.
Here is my code:
function valid_email($email) {
return !!filter_var($email, FILTER_VALIDATE_EMAIL);
}
I don't know how/where to put the specific domain validation part
Modify your function as follows:
function valid_email($email) {
$result = false;
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$server = strstr($email, '#');
if ($server == '#hotmail.com') {
$result = true;
}
}
return $result;
}
Or in one line:
function valid_email($email) {
return !!filter_var($email, FILTER_VALIDATE_EMAIL) && '#hotmail.com' == strstr($email, '#');
}
Info about strstr
Related
I am trying to validate email in php using ereg, where I am not allowed to enter more than two dots after # and it can't begin with any special character, how can I do it.
function chk($a)
{
$pattern = "^([A-Za-z0-9\.|-|_]{1,60})([#])";
$pattern .="([A-Za-z0-9\.|-|_]{1,60})(\.)([A-Za-z]{2,3})$";
if (!#ereg($pattern, $a))
return false;
else
return true;
}
Please don't roll your own email validation.
if(filter_var($email, FILTER_VALIDATE_EMAIL) === true){
return true;
} else {
return false;
}
preg_match("/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/",'test#test.co.in.');
function custom_email_confirmation_validation_filter( $your_email ) {
if(!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $your_email )){
return 'invalid';
}
if( substr_count($your_email, '.') > 3){
return 'invalid 1';
}
return 'valid';
}
echo custom_email_confirmation_validation_filter('golapk.kkk.khazi#gmail.com');
I am trying to read all lines from a file and than see if a given string contains any of these lines.
My code
$mails = file('blacklist.txt');
$email = "hendrik#anonbox.net";
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) > 0) {
$fail = true;
}
}
if($fail) {
echo "Fail";
} else {
echo "you can use that";
}
The blacklist.txt can be found here http://pastebin.com/aJyVkcNx.
I would expect strpos return a position for at least one string in the blacklist, but it does not. I am guessing that somehow I am generating not the kind of values within the $mails as I am expecting.
EDIT this is print_r($mails) http://pastebin.com/83ZqVwHx
EDIT2 some clarification: I want to see if a domain is within an email, even if the mail contains subdomain.domain.tld. And I tried to use !== false instead of my > 0 which yielded the same result.
You need to parse the email well since you're checking the domain of the email address if its inside the blacklist. Example:
$email = "hendrik#foo.anonbox.net";
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
preg_match('/#.*?([^.]+[.]\w{3}|[^.])$/', $email, $matches);
if(!empty($matches) && isset($matches[1])) {
$domain = $matches[1];
} else {
// not good email
exit;
}
// THIS IS FOR SAMPLES SAKE, i know youre using file()
$blacklist = explode("\n", file_get_contents('http://pastebin.com/raw.php?i=aJyVkcNx'));
foreach($blacklist as $email) {
if(stripos($email, $domain) !== false) {
echo 'you are blacklisted';
exit;
}
}
}
// his/her email is ok continue
strpos returns FALSE if the string was not found.'
Simply use this :
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) === false) {
$fail = true;
}
}
Or even better use this:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik#anonbox.net";
if(strpos($email, $blacklist) === false){
echo "fail";
} else {
echo "This email is not blacklisted";
}
You have found the common pitfall with the strpos function. The return value of the strpos function refers to the position at which it found the string. In this instance, if the string begins at the first character, it will return 0. Note that 0 !== false.
The correct way to use the function is:
if(strpos($email, $mail) !== false){
// the string was found, potentially at position 0
}
However, this function may not be necessary at all; if you are simply checking if $mail is the same as $email, instead of seeing if the string exists within a larger string, then just use:
if($mail == $email){
// they are the same
}
Though you might still use foreach, that’s array reduce pattern:
function check_against($carry, $mail, $blacklisted) {
return $carry ||= strpos($mail, $blacklisted) !== false;
};
var_dump(array_reduce($mails, "check_against", $email_to_check));
Hope it helps.
Yet another way to solve this. Works fine:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik#x.ip6.li";
$domain = substr(trim($email), strpos($email, '#')+1);
if(strpos($blacklist, $domain)){
echo "Your email has been blacklisted!";
}else{
echo "You are all good to go! not blacklisted :-)";
}
Goodluck!
I'm trying to find a solution to only validate emails with .edu extension in Wordpress using Ninja Forms plugin.
With Contact Form 7 I can something like this:
function is_edu($email) {
if(substr($email, -4) == '.edu') {
return true;
} else {
return false;
};
};
function custom_email_validation_filter($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
if($name == 'your-email') { // Only apply to fields with the form field name of "your-email"
$the_value = $_POST[$name];
if(!is_edu($the_value)){
$result['valid'] = false;
$result['reason'][$name] = 'This is not a .edu address!'; // Error message
};
};
return $result;
};
add_filter('wpcf7_validate_email','custom_email_validation_filter', 10, 2); // Email field
add_filter('wpcf7_validate_email*', 'custom_email_validation_filter', 10, 2); // Required Email field
Here is a regex you can use :
if(preg_match('/^[a-zA-z0-9]+#[a-zA-z0-9]+\.edu$/', $emailaddress)) {
//valid email address, start script
}
I imagien you know how to implement this into the plugin ?
This question already has answers here:
How to validate an Email in PHP?
(7 answers)
How to validate an email address in PHP
(15 answers)
Closed 9 years ago.
I want to validate the e-mail domain but I don't want to worry about any possible subdomain that may appears.
For example:
#abc.com
#a.abc.com
#b.abc.com
...
These should all be valid.
Also, I have a list of domains to validate, such as abc.com, xyz.com... how is the best way to validate e-mail domains from a list, including subdomains?
Thanks.
I decided to rewrite this to be more friendly so that you aren't restricted on what type of domain scheme you whitelist.
$whitelist = array("abc.com", "xyz.com", "specific.subdomain.com", "really.specific.subdomain.com"); //You can add basically whatever you want here because it checks for one of these strings to be at the end of the $email string.
$email = "#d.xyz.com";
function validateEmailDomain($email, $domains) {
foreach ($domains as $domain) {
$pos = strpos($email, $domain, strlen($email) - strlen($domain));
if ($pos === false)
continue;
if ($pos == 0 || $email[(int) $pos - 1] == "#" || $email[(int) $pos - 1] == ".")
return true;
}
return false;
}
So, you'd use this like:
if (validateEmailDomain($email, $whitelist))
//Do something.
You can also validate the domain using dns:
function validEmail($email)
{
$allowedDomains = array('abc.com');
list($user, $domain) = explode('#', $email);
if (checkdnsrr($domain, 'MX') && in_array($domain, $allowedDomains))
{
return true;
}
return false;
}
I wrote this function a while back. It may fill the requirements on what you're looking for. It does two things, validates the email address is a valid address and then validates if the domain name is a valid name against it's MX record in DNS.
function validate_email($email) {
// Check email syntax
if(preg_match('/^([a-zA-Z0-9\._\+-]+)\#((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,7}|[0-9]{1,3})(\]?))$/', $email, $matches)) {
$user = $matches[1];
$domain = $matches[2];
// Check availability of DNS MX records
if(getmxrr($domain, $mxhosts, $mxweight)) {
for($i=0;$i<count($mxhosts);$i++){
$mxs[$mxhosts[$i]] = $mxweight[$i];
}
// Sort the records
asort($mxs);
$mailers = array_keys($mxs);
} elseif(checkdnsrr($domain, 'A')) {
$mailers[0] = gethostbyname($domain);
} else {
$mailers = array();
}
$total = count($mailers);
// Added to still catch domains with no MX records
if($total == 0 || !$total) {
$error = "No MX record found for the domain.";
}
} else {
$error = "Address syntax not correct.";
}
return ($error ? $error : TRUE);
}
I wrote a simple example of the regular expression with the ability to check the list of domain.
<?php
$email = 'shagtv#a.xyz.com';
$domains = array('abc.com', 'xyz.com');
$pattern = "/^[a-z0-9._%+-]+#[a-z0-9.-]*(" . implode('|', $domains) . ")$/i";
if (preg_match($pattern, $email)) {
echo 'valid';
} else {
echo 'not valid';
}
?>
Well you should use some code like this:
<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
or this:
<?php
$email = "someone#exa mple.com";
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
}
else
{
echo "E-mail is valid";
}
?>
or this that you have to do a little modify with this page.
Hope it helps!
Very similar to this post: PHP Check domain of email being registered is a 'school.edu' address
However, you need to take it one step further. Once you have that split, look at parse_url
http://php.net/manual/en/function.parse-url.php and grab the HOST part.
I'm learning PHP and I'm trying to write a simple email script. I have a function (checkEmpty) to check if all the forms are filled in and if the email adress is valid (isEmailValid). I'm not sure how to return true checkEmpty funciton. Here's my code:
When the submit button is clicked:
if (isset($_POST['submit'])) {
//INSERT FORM VALUES INTO AN ARRAY
$field = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($field);
checkEmpty($name, $email, $message);
function checkEmpty($name, $email, $message) {
global $name_error;
global $mail_error;
global $message_error;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$name_error = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$mail_error = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$mail_error = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$message_error = "<span class='error_text'>* Please enter your message</span>";
}
}
// This function tests whether the email address is valid
function isValidEmail($email){
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (eregi($pattern, $email))
{
return true;
} else
{
return false;
}
}
I know I shouldn't be using globals in the function, I don't know an alternative. The error messages are display beside each form element.
First of all, using global is a sin. You are polluting global namespace, and this is bad idea, except little ad-hoc scripts and legacy code.
Second, you are misusing isset - for two reasons:
a ) in given context you pass variable $name to function, so it is always set
b ) empty checks whether variable is set or not
Third, you should separate validation from generating html.
Fourth, you can use filter_var instead of regular expression to test if mail is valid.
Last, your code could look like that:
<?php
if (isset($_POST['submit'])) {
$fields = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($fields);
$errors = validateFields($name, $email, $message);
if (!empty($errors)){
# error
foreach ($errors as $error){
print "<p class='error'>$error</p>";
}
} else {
# all ok, do your stuff
} // if
} // if
function validateFields($name, $email, $post){
$errors = array();
if (empty($name)){$errors[] = "Name can't be empty";}
if (empty($email)){$errors[] = "Email can't be empty";}
if (empty($post)){$errors[] = "Post can't be empty";}
if (!empty($email) && !filter_var($email,FILTER_VALIDATE_EMAIL)){$errors[] = "Invalid email";}
if (!empty($post) && strlen($post)<10){$errors[] = "Post too short (minimum 10 characters)";}
# and so on...
return $errors;
}
First of all, you should really re-think your logic as to avoid global variables.
Eitherway, create a variable $success and set it to true in the top of your functions. If any if statement fails, set it to false. Then return $success in the bottom of your function. Example:
function checkExample($txt) {
$success = true;
if (isset($txt) === true && empty($txt) === true) {
$error = "<span class='error_text'>* Please enter your example text</span>";
$success = false;
}
return $success;
}
I'm not sure this is what you want, the way I see it, you want $mail_error, $message_error and $name_error to be accessible from outside the function. If that's the case, what you need is something like this:
function checkEmpty($name, $email, $message) {
$results = false;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$results['name_error'] = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$results['mail_error'] = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$results['mail_error'] = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$results['message_error'] = "<span class='error_text'>* Please enter your message</span>";
}
return $results;
}
$errors = checkEmpty($name, $email, $message);
now you can test for errors
if($errors){
extract ($errors); // or simply extract variables from array to be used next to form inputs
} else {
// there are no errors, do other thing if needed...
}