完全验证带有或不带有http或https的URL [英] Completely validate URL with or without http or https

查看:135
本文介绍了完全验证带有或不带有http或https的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对PHP中的URL验证进行了一些研究,发现StackOverflow上存在许多不同的答案,其中一些比其他答案要好,而另一些则已经过时了.

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.

我有一个用户可以在其中输入其网站网址的字段.用户应该能够以任何形式输入URL,例如:

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附带了用于验证URL的函数,但是,如果没有http://,则会将该网址标记为无效.

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

我如何验证带有或不带有http://https://的任何种类的URL,以确保URL有效?

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

谢谢.

推荐答案

使用您所说的filter_var(),但是根据定义,URL必须包含一个协议.仅使用http也会检查https:

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;

然后:

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

这篇关于完全验证带有或不带有http或https的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆