Reputation: 2226
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.
Upvotes: 7
Views: 20246
Reputation: 480
The question is from a decade ago, and my answer might might not be applicable for all cases, but probably the best approach is to send a small request to the url and see if it works.
Upvotes: 0
Reputation: 11
You can create a custom validation rule then add the following method in it :
protected function prepareForValidation()
{
$urlWithHttp = strpos($this->url, 'http') !== 0 ? "http://$this->url" : $this->url;
$this->merge([
'url' => $urlWithHttp,
]);
}
Upvotes: 0
Reputation: 78994
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
}
Upvotes: 25
Reputation: 43
You could also let html validate the url:
Website: <input type="url" name="website" required pattern="https?://.+">
Upvotes: -2
Reputation: 2893
I've also seen this used:
$url = "http://example.com";
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
echo "URL is valid";
}
else {
echo "URL is invalid";
}
Source: http://codekarate.com/blog/validating-url-php
Upvotes: 3