Better way to validate a URL in PHP

2020-03-30 01:46发布

问题:

I've been reading various posts on Stack Overflow to try and find an ideal way to validate a URL in PHP. My research has come up with three possible solutions, however, none of them are ideal.

The three methods mentioned are regex, filter_var ($url, FILTER_VALIDATE_URL) and parse_url (). The problems with the first approach are already well known, and the most comprehensive validation regex I could find spanned pages. The filter_var function built into the PHP filtering extension appears to have faults, such as treating a url like http://... as valid. The parse_url method is using a function that was never intended for URL validation and therefore can't be depended on for this task.

Are there any other options regarding URL validation in PHP that I may have missed?

回答1:

How about you combine filter_var (which basically is a regex check that spans pages) with additional regex check for cases you don't think are covered well by it?



回答2:

I ussually use parse_url() for check/validate url (in most case, i need to determine whether the url is already a valid url or a relative url)

if (parse_url($url, PHP_URL_SCHEME) != '')
{
   // Url is absolute
}
else
{
   // Url is not an absolute url, and therefore, need more validation...
}