Bagwell Bagwell - 1 year ago 78
PHP Question

Completely validate URL

I've done some researching on validating URLs in PHP and found that there are many different answers on StackOverflow, some better than others, and some very old and outdated.

I have a field where users can input their website's url. The user should be able to enter the URL in any form, for example:

PHP comes with a function to validate URLs, however, it marks the URL as invalid if it doesn't have

How can I validate any sort of URL, with or without
, that would ensure the URL is valid?


Answer Source

Use filter_var() as you stated, however, by definition a URL must contain a protocol:

$url = strpos($url, 'http') !== 0 ? "http://$url" : $url;


if(filter_var($url, FILTER_VALIDATE_URL)) {
} else {
    //not valid