Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completely validate URL with or without http or https

Tags:

regex

php

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:

example.com
www.example.com
http://example.com
http://www.example.com
https://example.com
https://www.example.com

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

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

Thanks.

like image 245
Bagwell Avatar asked Dec 18 '13 22:12

Bagwell


1 Answers

Use filter_var() as you stated, however, by definition a URL must contain a protocol. Using just http will check for https as well:

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

Then:

if(filter_var($url, FILTER_VALIDATE_URL)) {
    //valid
} else {
    //not valid
}
like image 200
AbraCadaver Avatar answered Oct 11 '22 15:10

AbraCadaver