Validating URL in PHP without regular expressions

Validating many things in PHP is often done using regular expressions, but since those might be complicated to understand, versions of PHP later than 5.20 have new validating mechanism built in. It’s done using filter_var function. Here are some basic examples of both old (regular expression) and new (filter_var) validation functions:

Validating URL using regular expressions:

function isValidURL($url) {
	return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}

Validating URL using filter_var:

function isValidURL($url) {
	if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) return true;
	else return false;
}

You will notice FILTER_VALIDATE_URL and FILTER_FLAG_HOST_REQUIRED flags in filter_var function. There are many more and here are some more real world examples

var_dump((bool) filter_var('http://www.website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED));
var_dump((bool) filter_var('http://website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED));
var_dump((bool) filter_var('www.website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED));
var_dump((bool) filter_var('website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED));

Output:

bool(true)
bool(true)
bool(true)
bool(false)

Here are some most common URL validation flags explanation

  • FILTER_FLAG_SCHEME_REQUIRED – Require the scheme (eg, http://, ftp:// etc) within the URL.
  • FILTER_FLAG_HOST_REQUIRED – Require host of the URL (eg, www.google.com)
  • FILTER_FLAG_PATH_REQUIRED – Require a path after the host of the URL. ( eg, /folder/file.ext)
  • FILTER_FLAG_QUERY_REQUIRED – Require a query at the end of the URL (eg, ?key=value)

Validating Email using regular expressions:

function isValidEmail($email) {
    return preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email);
}

Validating Email using filter_var:

function isValidEmail($email) {
	if (filter_var($email, FILTER_VALIDATE_EMAIL)) return true;
	else return false;
}

Conclusion
Validating URLs, Emails, IPs and many other things using regular expressions is history now. Code for validations using filter_var is easier to understand easier to write and looks more php geeky. You don’t have to search for “working” regular expressions for your validations… It’s all there and it’s well documented and all you need is just need to use it.
Continue Reading

Tags: url validation in javascript without http, php validate url