Проверка существования ссылки php

How to Validate URL with PHP

Any time a user submits a URL, it is crucial to investigate whether the given URL is valid or not. In this short tutorial, you will find the easiest and most efficient way to validate a URL with the help of PHP. Check out the options below.

The First Option is Using filter_var

The first efficient way of validating a URL is applying the filter_var function with the FILTER_VALIDATE_URL filter. So, the following code should be used for checking whether the ($url) variable is considered a valid URL:

 $url = "http://www.w3docs.com"; if (!filter_var($url, FILTER_VALIDATE_URL) === false) < echo "$url is a valid URL"; > else < echo "$url is not a valid URL"; > ?>

The Second Option is Using preg_match

For checking whether the syntax of a URL address is valid, you are also recommended to use the preg_match regular expression. Also, in the URL, dashes are allowed by regular expressions.

In case there exists an invalid syntax, an error message turns out, as demonstrated in the example below:

 $website = 'https://www.w3docs'; $pattern = '/^(https?:\/\/)?([\da-z.-]+)\.([a-z.])([\/\w.-]*)*\/?$/'; if (!preg_match($pattern, $website)) < echo "Invalid URL"; > else < echo "URL is valid: " . $website; > ?>

Describing the filter_var Function

This function is commonly used in PHP for filtering a variable with a given filter. It includes three parameters such as variable, filter, and options.

Describing the preg_match() Regex

The preg_match() regular expression is aimed at searching the string for a pattern. True will be returned when the pattern is there, and, otherwise, false.

Источник

check if a string is a URL [duplicate]

I’ve seen many questions but wasn’t able to understand how it works as I want a more simple case. If we have text, whatever it is, I’d like to check if it is a URL or not.

$text = "something.com"; //this is a url if (!IsUrl($text))< echo "No it is not url"; exit; // die well >else < echo "Yes it is url"; // my else codes goes >function IsUrl($url) < // . >

8 Answers 8

The code below worked for me:

if(filter_var($text, FILTER_VALIDATE_URL)) < echo "Yes it is url"; exit; // die well >else < echo "No it is not url"; // my else codes goes >

You can also specify RFC compliance and other requirements on the URL using flags. See PHP Validate Filters for more details.

your first line should be checking for false, so its actually if(!filter_var($text, FILTER_VALIDATE_URL)) or flip your if/else.

PHP’s filter_var function is what you need. Look for FILTER_VALIDATE_URL . You can also set flags to fine-tune your implementation.
No regex needed.

However this is only true if you use http in front of the URL. For instance, www.google.com will not be validated correctly.

Technically, according to the definition of a URL (or URI) it requires a protocol (http, https, etc) to be the first thing in the string. What you’re describing is just the domain and path portions of the full URL.

)"; // Host or IP $regex .= "(\:4)?"; // Port $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor if(preg_match("/^$regex$/i", $url)) // `i` flag for case-insensitive < return true; >?> 

but your example URL is over simplified, (\w+)\.(\w+) would match it. somebody else mentioned filter_var which is simply a filter_var($url, FILTER_VALIDATE_URL) but it doesn’t seem to like non-ascii characters so, beware.

I would recommend looking into the GET Query. Didn’t parse a youtube link. I need to make some changes to make them work based on: stackoverflow.com/questions/23959352/…

Check if it is a valid url (example.com IS NOT a valid URL)

 if(!isValidURL($fldbanner_url)) < $errMsg .= "* Please enter valid URL including http://
"; >

Regexes are a poor way to validate something as complex as a URL.

PHP’s filter_var() function offers a much more robust way to validate URLs. Plus, it’s faster, since it’s native code.

If you look above, the original question does not mention anything about PHP. If anything it’s asking how to achieve the outcome without the use of JS. So in actual fact, your answer is not appropriate for the question asked. Furthermore, the answer Jack approved should not have been given the green tick, as it’s a PHP answer, to a non-PHP question. Yet another example of poor moderation IMO.

The question is tagged with «php». The example code provided is PHP. The asker probably should have been more explicit with his question—but it’s clear from context that he’s trying to validate the URL server-side, and is using PHP as his server-side language. And I am now done with this silly argument 🙂

Источник

Проверка валидности url. PHP

Но эта штука все время выдает «no». Мне кажется это из за кириллицы. Ее убирать нельзя. сайт.рф ведь. Помогите пожалуйста, как исправить. Я работаю в кодировке UTF-8 Вот нарыл по-лучше, но не могу кириллицу добавить.. Помогите плиз

function is_url($in)< $w = "a-z0-9"; $url_pattern = "#( (?:f|ht)tps?://(?:www.)? (?:[$w\\-.]+/?\\.[a-z])/? (?:[$w\\-./\\#]+)? (?:\\?[$w\\-&=;\\#]+)? )#xi"; $a = preg_match($url_pattern,$in); return $a; > 

6 ответов 6

В плане проверки русскоязычных доменов могу рекомендовать смотреть в сторону конвертации в IDN, т.е. к виду xn--af1bc.net тогда проблем с русским точно не будет. В стандартном наборе таких функций нет, только декодирование. Если есть возможность поставить соответствующий модуль PECL, то на мой взгляд это идеальное решение.

Если вам надо проверить, существует ли указанный адрес или нет, то есть способ гораздо проще:

$url = 'http://hashcode.ru'; if(get_headers($url, 1))

Потому, как http://www.chopopalo.com — проверку регуляркой пройдет, но вот сайта такого, просто не существует.

только перед таким смелым запросом я бы добавил if(checkdnsrr($domain,’A’) && get_headers($url, 1)) что бы не получить ошибку. Автор, думаю это действительно самый подходящий вариант

На самом деле это не нужно. Это много пользовательский сайт, и пользователи сами должны беспокоится о существовании сайта по указываемой ссылке

Вообще не встречал адекватных регулярок для проверки url. Так что для таких случаев нужно четко формировать требования к урлу, а потом уже составлять выражение.

$a у Вас не соответствует выражению, в то время как «http://www.site.ru» — вполне подойдет. А вот «http://subdomen.site.ru» — уже не влезет. Если урл еще ведет на внутреннюю страницу — тоже не подходит. А зачастую главными являются страницы вида «http://site.ru/en/index.html». И т.д. И т.п.

С русским языком проблем быть не должно, а если всё-таки возникают — значит у Вас старое ПО, пропишите в регулярку весь алфавит.

Требование самое сложное)) URL с GET параметрами и hash’ами. Я обновил шапку и ф-ия, которую добавил удовлетворяет всем моим требованиям, но я не могу добавить кириллицу. Прошу помощи 🙂

Источник

Читайте также:  Css позиционирование одного элемента относительно другого
Оцените статью