To check if a URL or an email address is valid, the common solution is regular expressions. For instance, to validate an email address in PHP, I would use:
if (preg_match('|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $email)) {
// $email is valid
}
A simpler and more forgiving one would be:
|^\S+@\S+\.\S+$|
Which is usually quite enough for signup forms in preventing stupid typo errors. You get to validate the email by a validation link sent to the address anyway, as a final call whether the address is valid or not. For those who are obsessively curious, this may serve you well.
For URL, you can use this one:
|^\S+://\S+\.\S+.+$|
Or you can use one that is insanely detailed in addressing what a valid URL should be.
The filter_var() function of PHP5
What we are talking about here really is the filter_var() function of PHP5 that simplifies the URL and email validation by a large degree. To validate an email:
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
// $email contains a valid email
}
To validate a URL:
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
// $url contains a valid URL
}
While filter_var() is meant to return the filtered results of the input according to the filter type specified, such as FILTER_VALIDATE_EMAIL or FILTER_VALIDATE_URL, you can generally use it to see if a valid email or a valid URL can be extracted from something. Better yet, filter and get the results first, use the result if it is good or abandon it when it is false:
$filtered_email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($filtered_email !== false) {
// $filtered_email is the valid email got out of $email
} else {
// nothing valid can be found in $email
}
Same applies to FILTER_VALIDATE_URL. Here’s a full list of filter types of filter_var() you can take advantage of.
Pingback: PHP: How to detect / get the real client IP address of website visitors?
This is a nice example. Its easy to understand..
doing a good job.
Thanks a lot..!
I love the filter_var function for validation, EXCEPT for this one fact:
The FILTER_VALIDATE_URL filter has a bug in it that fails url hostnames with hyphens in them, as of 5.2.13. That sucks!
if (filter_var($url, FILTER_VALIDATE_URL) !== false)
==> if (filter_var($url, FILTER_VALIDATE_URL))
it’s the same !!!!
and more understandable
Thanks
Nice to see a clear and clean explanation
Keep posting
be careful, the filter functions in php are really poor.
seems to be false security features like safemode was…..
check yourself, insert some javascript code to your url and you’ll see it wont work.
e.g.
“>alert(‘hacked’)
is a valid url for php, ouch!
i dont believe in php filter functions at all!