Validate URL and Email function using PHP Filters

Posted By: Ian on Mar 01, 2014 in PHP, Snippets
Last modified on January 29th, 2015 at 9:31 pm,

In PHP 5.2 filter functions come installed and enabled by default and today were going to use two of them, one to validate URLs and the other email addresses, replacing the need to use regular expressions like preg_match.

For the purpose of this demonstration
<?php
$email = "ianjgough@aol.com";
$url = "http://ianjgough.com";
 
function validate($type, $value)
{
if ($value) {
if ($type == "email") {
$check = filter_var($value, FILTER_VALIDATE_EMAIL);
} else {
$check = filter_var($value, FILTER_VALIDATE_URL);
}
$status = 'The ' . $type . ' ' . $value . ' is ' . ($check ? 'valid' : 'invalid');
}
echo $status;
}
 
validate("email",$email);
echo "<br />";
validate("url",$url);
?>

For your forms your probably want to use this
<?php
function validate($type, $value)
{
if ($value) {
if ($type == "email") {
$check = filter_var($value, FILTER_VALIDATE_EMAIL);
} else {
$check = filter_var($value, FILTER_VALIDATE_URL);
}
$status = ($check) ? true : false;
}
return $status;
}
 
if(validate("url",$url)){
//Do your stuff here
}
?>


Check which filters are available for you
<?php
foreach (filter_list() as $filter) {
if ($filter == NULL) {
echo "No filters were found!";
} else {
echo $filter."<br />";
}
}
?>

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125