Validate url with php

Как проверить URL в PHP

Считаете ли вы этот сниппет полезным? То поделитесь этим с друзьями или коллегами. Это поможет нам сделать наши бесплатные веб-инструменты лучше.

1) Самый простой способ проверить, правильно ли сформирован адрес электронной почты — использовать функцию filter_var():

Фильтр FILTER_VALIDATE_URL проверяет URL.
Возможные флаги:

  • FILTER_FLAG_SCHEME_REQUIRED — URL должен соответствовать RFC (например https://wtools)
  • FILTER_FLAG_HOST_REQUIRED — URL должен включать имя хоста (например https://wtools.io)
  • FILTER_FLAG_PATH_REQUIRED — URL должен иметь путь после имени домена (например wtools.io/php-snippets/)
  • FILTER_FLAG_QUERY_REQUIRED — URL должен содержать строку запроса (например wtools.io?name=Peter&age=37)

2) Если вы хотите узнать, действительно ли существует URL-адрес (через CURL):

function urlExist($url)else < return true; >> $url = 'https://wtools.io'; if ( urlExist($url) ) $output = "$url - действительный URL"; else $output = "$url не является действительным URL"; echo $output;

3) Проверить через регулярное выражение с http или https:

)?(?:$|[?\/#])/i'; if (preg_match($pattern, $url)) < $output = "$url - действительный URL"; >else < $output = "$url не является действительным URL"; >echo $output;

Источник

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.

Читайте также:  Python количество ссылок на объект

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.

Источник

How To Validate URL In PHP With Regex

In this article, we will see how to validate URLs in PHP with regular expressions. Also, you can implement it in laravel or PHP. here we will give you an example of validating URL with a regular expression and without regular expression. So, you can both way to implement validate URL in PHP or laravel.

When a URL is submitted from a form input by the user, it is very important to check this URL is valid or not before taking any action on it. So, here we will provide the simple PHP code to validate URL in PHP.

So, let’s see validate URL, PHP gets URL, URL validation regex laravel, valid URL using a regular expression, how to validate URL in laravel, URL validation regex PHP.

PHP provide filter_var() inbuilt function with FILTER_VALIDATE_URL filter. So, we can easily validate a URL in PHP using javascript regex or regular expression.

The FILTER_VALIDATE_URL filter validates a URL.

Possible flags of validating URL in PHP.

FILTER_FLAG_HOST_REQUIRED - URL must include hostname (like https://www.techsolutionstuff.com) FILTER_FLAG_PATH_REQUIRED - URL must have a path after the domain name (like www.techsolutionstuff.com/post)

Above function is simply to check URL validation. If you want to check or validate URLs manually or more securely then you can use regular expression. So, here I will give an example of code.

)"; $regex .= "(\:1)?"; $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; $url = 'https://techsolutionstuff.com/'; if (preg_match("/^$regex$/i", $url))

You might also like :

  • Read Also : How To Generate QRcode In Laravel
  • Read Also : Google Map With Draggable Marker Example
  • Read Also : How To Create Dependent Dropdown In Laravel
  • Read Also : How To Get Selected Checkbox List Value In Jquery

Источник

PHP Forms — Validate E-mail and URL

This chapter shows how to validate names, e-mails, and URLs.

PHP — Validate Name

The code below shows a simple way to check if the name field only contains letters, dashes, apostrophes and whitespaces. If the value of the name field is not valid, then store an error message:

$name = test_input($_POST[«name»]);
if (!preg_match(«/^[a-zA-Z-‘ ]*$/»,$name)) $nameErr = «Only letters and white space allowed»;
>

The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

PHP — Validate E-mail

The easiest and safest way to check whether an email address is well-formed is to use PHP’s filter_var() function.

In the code below, if the e-mail address is not well-formed, then store an error message:

$email = test_input($_POST[«email»]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $emailErr = «Invalid email format»;
>

PHP — Validate URL

The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:

PHP — Validate Name, E-mail, and URL

Now, the script looks like this:

Example

// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = «»;
$name = $email = $gender = $comment = $website = «»;

if ($_SERVER[«REQUEST_METHOD»] == «POST») if (empty($_POST[«name»])) $nameErr = «Name is required»;
> else $name = test_input($_POST[«name»]);
// check if name only contains letters and whitespace
if (!preg_match(«/^[a-zA-Z-‘ ]*$/»,$name)) $nameErr = «Only letters and white space allowed»;
>
>

if (empty($_POST[«email»])) $emailErr = «Email is required»;
> else $email = test_input($_POST[«email»]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $emailErr = «Invalid email format»;
>
>

if (empty($_POST[«website»])) $website = «»;
> else $website = test_input($_POST[«website»]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match(«/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|. ;]*[-a-z0-9+&@#\/%=~_|]/i»,$website)) $websiteErr = «Invalid URL»;
>
>

if (empty($_POST[«comment»])) $comment = «»;
> else $comment = test_input($_POST[«comment»]);
>

if (empty($_POST[«gender»])) $genderErr = «Gender is required»;
> else $gender = test_input($_POST[«gender»]);
>
>
?>

The next step is to show how to prevent the form from emptying all the input fields when the user submits the form.

Источник

Оцените статью