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...
Related
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.
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
}
}
I already am using php's filter_var($email, FILTER_VALIDATE_EMAIL) to find out if the address is valid email.
I'm just gonna go ahead and block .ru email addresses. What regex and code should I use? Any other spammy tlds or addresses that you block would be appreciated as well.
I have tried this, but want to be sure I'm catching it correctly and catch other spammy emails.
function endsWith($haystack, $needle){
$length = strlen($needle);
return (substr($haystack, -$length) === $needle);
}
Thanks VG:
function russianEmail($email,$endings = array('\.ru')){
return (preg_match('/('.implode('|', $endings).')$/i', $email))?true:false;
}
You can match multiple domain zones (or just endings) with following code:
$endings = array('\.ru'); // you can add zones here
preg_match('/('.implode('|', $endings).')$/i', $email);
This regex is also case-insensitive.
This is what I use (not all my own work however):
Replace the link to russianbrides.com with whatever dark place you want to send the spammer.
function my_inArray($needle, $haystack) {
// this function allows wildcards in the array to be searched
foreach ($haystack as $value) {
if (true === fnmatch($value, $needle)) {
return true;
}
}
return false;
}
// Blocking Wildcard Emails.
$deny = array(
"*#hotmobilephoneoffers.com",
"*#*.ru",
"*#*.su",
);
if (my_inarray (strtolower($email_from), $deny)) {
header("location: http://www.russianbrides.com/");
exit();
}
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');
?>
How can I validate the input value is a valid email address using php5. Now I am using this code
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;
}
}
but it shows deprecated error. How can I fix this issue. Please help me.
You can use the filter_var() function, which gives you a lot of handy validation and sanitization options.
filter_var($email, FILTER_VALIDATE_EMAIL)
PHP Manual filter_var()
Available in PHP >= 5.2.0
If you don't want to change your code that relied on your function, just do:
function isValidEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
Note: For other uses (where you need Regex), the deprecated ereg function family (POSIX Regex Functions) should be replaced by the preg family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.
Update 1: As pointed out by #binaryLV:
PHP 5.3.3 and 5.2.14 had a bug related to
FILTER_VALIDATE_EMAIL, which resulted in segfault when validating
large values. Simple and safe workaround for this is using strlen()
before filter_var(). I'm not sure about 5.3.4 final, but it is
written that some 5.3.4-snapshot versions also were affected.
This bug has already been fixed.
Update 2: This method will of course validate bazmega#kapa as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: bazmega#kapa.com. As suggested in this blog post (link posted by #Istiaque Ahmed), you can augment filter_var() with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL)
&& preg_match('/#.+\./', $email);
}
As #Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.
See the notes at http://www.php.net/manual/en/function.ereg.php:
Note:
As of PHP 5.3.0, the regex extension is deprecated in favor of
the PCRE extension. Calling this
function will issue an E_DEPRECATED
notice. See the list of differences
for help on converting to PCRE.
Note:
preg_match(), which uses a Perl-compatible regular expression
syntax, is often a faster alternative
to ereg().
This is old post but I will share one my solution because noone mention here one problem before.
New email address can contain UTF-8 characters or special domain names like .live, .news etc.
Also I find that some email address can be on Cyrilic and on all cases standard regex or filter_var() will fail.
That's why I made an solution for it:
function valid_email($email)
{
if(is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email))
return false;
else
{
$email=trim(strtolower($email));
if(filter_var($email, FILTER_VALIDATE_EMAIL)!==false) return $email;
else
{
$pattern = '/^(?!(?:(?:\\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';
return (preg_match($pattern, $email) === 1) ? $email : false;
}
}
}
This function work perfectly for all cases and email formats.
I always use this:
function validEmail($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;
}
User data is very important for a good developer, so don't ask again
and again for same data, use some logic to correct some basic error in data.
Before validation of Email: First you have to remove all illegal characters from email.
//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
after that validate your email address using this filter_var() function.
filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email
For e.g.
<?php
$email = "john.doe#example.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $email." is a valid email address";
} else {
echo $email." is not a valid email address";
}
?>
Use:
or "filter_var" from http://php.net/manual/en/function.filter-var.php
var_dump(filter_var('bob#example.com', FILTER_VALIDATE_EMAIL));
or "EmailValidator" from https://github.com/egulias/EmailValidator
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
new RFCValidation(),
new DNSCheckValidation()
]);
$validator->isValid("example#example.com", $multipleValidations); //true
take several care, a address as iasd#x.z-----com is INVALID, but filter_var() return true, many others strings (emails) INVALIDS return true using filter_var().
for validate email I use this function:
function correcorre($s){// correo correcto
$x = '^([[:alnum:]](_|-|\.)*)*[[:alnum:]]+#([[:alnum:]]+(-|\.)+)*[[:alnum:]]+\.[[:alnum:]]+$';
preg_match("!$x!i", $s, $M);
if(!empty($M[0]))return($M[0]);
}
please improve and share, thanks