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

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);
}
?>

Related

email domain validation in php on windows

I am asking for an email address through a form in my website. I want to validate the domain so that I can prevent fake entries I am getting right now. I am using the following code, but it dose not seem to work :
function myCheckDNSRR($hostName, $recType = '')
{
if(!empty($hostName)) {
if( $recType == '' ) $recType = "MX";
exec("nslookup -type=$recType $hostName", $result);
// check each line to find the one that starts with the host
// name. If it exists then the function succeeded.
foreach ($result as $line) {
if(eregi("^$hostName",$line)) {
echo "valid email";
}
}
// otherwise there was no mail handler for the domain
echo "invalid email";
}
echo "invalid EMAIL";
}
I am new to this and used this code from here
Please guide me. Thanks.
I guess you can simply ping like this.
function myCheckDNSRR($email_address)
{
if(!empty($email_address)) {
$hostName=strstr($email_address, '#');
$hostName=str_replace("#","www.",$hostName);
exec("ping " . $hostName, $output, $result);
if ($result == 0){
echo "valid email";
}
else{
echo "invalid email";
}
}
}
call it like
echo myCheckDNSRR("sample#gmail.com");
Use a validation lib like https://docs.zendframework.com/zend-validator/validators/email-address/
$validator = new Zend\Validator\EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
Create a table in your DB for storing an email link code. When someone registers, mark the user as unactivated until he clicks the link in the email. This way, you know it's real, and can activate the user.

php integrated function form mail validation doesnt work FILTER_VALIDATE_EMAIL

I have the following script that checks emails and do something with them if they are correct formatted.. I am using FILTER_VALIDATE_EMAIL for this
Here is the code:
if(!empty($_POST['maillist'])){
$_POST['maillist'] = 'mariatettamanti#gmail.com,
H0889#sofiaertel.com,sdfd#sfs.com,';
$mails = explode(',',$_POST['maillist']);
foreach($mails as $mail){
if(!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = $mail." - Invalid email format<br />";
}else{
echo 'do job with this mail';
}
}
}
As you can see mails are formatted as mails but the function prints only first mail as correct and the rest as wrong.. Why is that? What am I missing? Thanks
Problem is with last comma in your email address. It create and empty value at the end . To avoid this you use isset()
if (!empty($_POST['maillist'])) {
$_POST['maillist'] = 'H0889#sofisadatel.com,info#daddsadyomiaasdmi.com,info#hotsdaelmidasami.com,';
$mails = explode(',', $_POST['maillist']);
foreach ($mails as $mail) {
if (isset($mail) && $mail != "") {// check for empty email
if(!filter_var(trim($mail), FILTER_VALIDATE_EMAIL)) {
echo $emailErr = $mail . " - Invalid email format<br />";
} else {
echo 'do job with this mail';
}
}
}
}

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

function eregi() is deprecated in email validation [duplicate]

This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 9 years ago.
Hi ı know that we do not eregi but preg_match but when ı change only eregi code it doesnt work, how can ı change the code below please just a little help, ı am a newbie
function verify_valid_email($emailtocheck)
{
$eregicheck = "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+#([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.)+[a-zA-Z]{2,4}\$";
return eregi($eregicheck, $emailtocheck);
}
function verify_email_unique($emailtocheck)
{
global $config,$conn;
$query = "select count(*) as total from members where email='".mysql_real_escape_string($emailtocheck)."' limit 1";
$executequery = $conn->execute($query);
$totalemails = $executequery->fields[total];
if ($totalemails >= 1)
{
return false;
}
else
{
return true;
}
}
If you need to validate e-mail addresses, you can look at this page which provides a working example using only filter_var() :
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
};
So in your code, you should just drop all the regex/eregi stuff and use this instead :
return filter_var($emailtocheck, FILTER_VALIDATE_EMAIL);
If you want to do it this way, you can base yourself on the following methods:
<?php
$email = \"abc123#somewhere\"; // Invalid email address
//$email = \"somebody#somesite.com\"; // Valid email address
// Set up regular expression strings to evaluate the value of email variable against
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
// Run the preg_match() function on regex against the email address
if (preg_match($regex, $email)) {
echo $email . \" is a valid email. We can accept it.\";
} else {
echo $email . \" is an invalid email. Please try again.\";
}
?>
or:
$string = "$emailtocheck";
if (preg_match(
'/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/',
$string)) {
echo "Successful.";
}
or:
<?php
$email = "abc123#sdsd.com";
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
echo $email . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
?>
Source: https://stackoverflow.com/a/13719991/1415724
or:
<?php
// check e-mail address
// display success or failure message
if (!preg_match("/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*#([a-zA-Z0-9_-
])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/", $_POST['e-mail'])) {
die("Invalid e-mail address");
}
echo "Valid e-mail address, processing...";
?>
Source: http://www.techrepublic.com/article/regular-expression-engine-simplifies-e-mail-validation-in-php/
Plus, you can try what André Daniel wrote as an answer as well. You have many choices.

Best email validation function in general and specific (college domain)?

I know email validation is one of those things which is not the funniest thing on the block. I'm starting up a website and i want to limit my audience to only the people in my college and i also want a preferred email address for my user. So this is a two part question.
Is there a really solid php function out there for email validation?
Can I validate an email from a specific domain. I dont want to just check if the domain exists, because I know www.mycollege.edu exists already. Is there really anyway to validate that the user has a valid #mycollege.edu web address?
This is what I use:
function check_email_address($email) {
// First, we check that there's one # symbol, and that the lengths are right
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
EDIT Replaced depreciated ereg with preg_match for PHP 5.3 compliance
If you really want to make sure its valid make your signup form send them an email with a URL link in that they have to click to validate.
This way not only do you know the address is valid (because the received the email), but you also know the owner of the account has signed up (unless someone else knows his login details).
To make sure it ends correctly you could use explode() on the '#' and check the second part.
$arr = explode('#', $email_address);
if ($arr[1] == 'mycollege.edu')
{
// Then it's from your college
}
PHP also has it's own way of validating email addresses using filter_var: http://www.w3schools.com/php/filter_validate_email.asp
This should work:
if (preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])#mycollege.edu$/', $email)) {
// Valid
}
Read here
http://ru2.php.net/manual/en/book.filter.php
Or in short
var_dump(filter_var('bob#example.com', FILTER_VALIDATE_EMAIL));
this might be a better solution. many answered already, eventhough its little different.
$email = "info#stakoverflow.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo $email ." is a valid email address";
} else {
echo $email ." is not a valid email address";
}
I hope this one has simple to use.
for any e-mail
([a-zA-Z0-9_-]+)(\#)([a-zA-Z0-9_-]+)(\.)([a-zA-Z0-9]{2,4})(\.[a-zA-Z0-9]{2,4})?
for php preg_match function
/([a-zA-Z0-9_-]+)(\#)([a-zA-Z0-9_-]+)(\.)([a-zA-Z0-9]{2,4})(\.[a-zA-Z0-9]{2,4})?/i
for #mycollege.edu
^([a-zA-Z0-9_-]+)(#mycollege.edu)$
for php preg_match function
/^([a-zA-Z0-9_-]+)(#mycollege.edu)$/i
PHP CODE
<?php
$email = 'tahir_aS-adov#mycollege.edu';
preg_match('/^([a-zA-Z0-9_-]+)(#mycollege.edu)$/i', $email, $matches);
if ($matches) {
echo "Matched";
} else {
echo "Not Matched";
}
var_dump($matches);
A simple function using filter_var in php
<?php
function email_validation($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
}
//Test
email_validation('johnson123');
?>

Categories