Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

php - Completely validate URL with or without http or https

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...