Php валидация e mail

Проверка правильности email на PHP

Проверка правильного формата вводимых данных очень важна в любых информационных системах. В данной статье, мы рассмотрим возможности PHP проверить, корректно ли указан адрес электронной почты (email). Обращу внимание, что речь идет лишь о проверке корректной структуры адреса. Дело в том, что адрес, может либо быть корректным (т.е. валидным), но при этом не существовать. Например, пользователь может просто ошибиться символом при вводе. Поэтому задача данной статьи – отсеять заведомо некорректные значения для email.

Как известно email состоит из двух основных частей. Например, адрес: MyEmail@myssite.ru.

Здесь, MyEmail – это непосредственный адрес (или логин) пользователя, а myssite.ru – адрес сайта, которому соответствует электронная почта.

Следовательно, проверка адреса на валидность заключается в том, что он должен соответствовать структуре:

логин_пользователя@доменное_имя.доменная_зона

В итоге, задача сводилась к построению регулярного выражения для проверки, соответствует ли проверяемая стока допустимым символам и структуре email. Но, начиная с PHP 5.2, появилась возможность выполнить эту проверку встроенной функцией filter_var(). Пример такой проверки:

$email = "MyEmail@mysite.ru";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) echo "Адрес указан корректно.";
>else echo "Адрес указан не правильно.";
>

В первый параметр функции указывается строковое значение, которое нужно проверить. Второй параметр – это идентификатор применяемого фильтра (в данном случае для проверки email). Функция filter_var() универсальна и может быть использована для проверки различных значений – числовое значение, логическое или проверка валидности IP-адреса.

Валидация email с использованием регулярного выражения PHP

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

$email = "MyEmail@mysite.ru";
if (preg_match("/^(?:[a-z0-9]+(?:[-_.]?[a-z0-9]+)?@[a-z0-9_.-]+(?:\.?[a-z0-9]+)?\.[a-z])$/i", $email)) echo "Адрес указан корректно.";
>else echo "Адрес указан не правильно.";
>

Если используете подобное регулярное выражение, стоит быть внимательным к возможным адресам. Например, в данный код решит, что введенное значение не email, если доменная зона будет более 5 символов или если адрес будет задан кириллицей. Поэтому, применяя его, учитывайте возможные вводимые значения.

Источник

Php валидация e mail

Пример #1 Валидация e-mail адреса, используя функцию filter_var()

$email_a = ‘joe@example.com’ ;
$email_b = ‘bogus’ ;

if ( filter_var ( $email_a , FILTER_VALIDATE_EMAIL )) echo «E-mail адрес ‘ $email_a ‘ указан верно.\n» ;
>
if ( filter_var ( $email_b , FILTER_VALIDATE_EMAIL )) echo «E-mail адрес ‘ $email_b ‘ указан верно.\n» ;
> else echo «E-mail адрес ‘ $email_b ‘ указан неверно.\n» ;
>
?>

Читайте также:  Svg border color css

Результат выполнения данного примера:

E-mail адрес 'joe@example.com' указан верно. E-mail адрес 'bogus' указан неверно.

Пример #2 Валидация IP-адреса, используя функцию filter_var()

if ( filter_var ( $ip_a , FILTER_VALIDATE_IP )) echo «IP-адрес ‘ $ip_a ‘ указан верно.» ;
>
if ( filter_var ( $ip_b , FILTER_VALIDATE_IP )) echo «IP-адрес ‘ $ip_b ‘ указан верно.» ;
>
?>

Результат выполнения данного примера:

Адрес '127.0.0.1' указан верно.

Пример #3 Дополнительные параметры функции filter_var()

$int_a = ‘1’ ;
$int_b = ‘-1’ ;
$int_c = ‘4’ ;
$options = array(
‘options’ => array(
‘min_range’ => 0 ,
‘max_range’ => 3 ,
)
);
if ( filter_var ( $int_a , FILTER_VALIDATE_INT , $options ) !== FALSE ) echo «Число A ‘ $int_a ‘ является верным (от 0 до 3).\n» ;
>
if ( filter_var ( $int_b , FILTER_VALIDATE_INT , $options ) !== FALSE ) echo «Число B ‘ $int_b ‘ является верным (от 0 до 3).\n» ;
>
if ( filter_var ( $int_c , FILTER_VALIDATE_INT , $options ) !== FALSE ) echo «Число C ‘ $int_c ‘ является верным (от 0 до 3).\n» ;
>

$options [ ‘options’ ][ ‘default’ ] = 1 ;
if (( $int_c = filter_var ( $int_c , FILTER_VALIDATE_INT , $options )) !== FALSE ) echo «Число C ‘ $int_c ‘ является верным (от 0 и 3).» ;
>
?>

Результат выполнения данного примера:

Число A '1' является верным (от 0 до 3). Число C '1' является верным (от 0 до 3).

Источник

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»;
>
>

Читайте также:  Настройка сессии PHP

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.

Источник

How to validate an email address in PHP

As all experienced developers know, it is essential to test and validate the information users can enter into a web form. This is even more important when it comes to email addresses, as when someone asks for information, you have to make sure that their email address is correct so they can receive the newsletters you create using your email builder or the answer to their requests.

Don’t reinvent the wheel.
Abstract’s APIs are production-ready now.

Abstract’s suite of API’s are built to save you time. You don’t need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that’s actually valuable for your app or business, and we’ll handle the rest.

Unfortunately, correctly verifying an email address is not an easy task, so we put together this detailed guide to help you out. Feel free to try out for yourself the code snippets we shared to experiment with validating email addresses in PHP. Also, as an alternative, check out our guide for validating emails with regex.

How to check the format of an email address in PHP

PHP natively provides a series of functions for validating and filtering, most notably the filter_var() function, which can validate email address format.

The filter_var() function accepts 3 parameters:

  • The first parameter is the variable to validate.
  • The second parameter defines the type of filter to be applied. The function allows you to check the format for IP addresses, domain names, and many others, including email addresses. The documentation provides a list of all usable filters.
  • The third parameter allows you to specify options that will determine the filter_var() function’s operation. These options depend on the type of filter that is being used.

To use filter_var() to perform email format validation, the second parameter must be set to FILTER_VALIDATE_EMAIL. If you know that the email address to validate contains Unicode characters, you must also specify the FILTER_FLAG_EMAIL_UNICODE option as the third parameter. Here are two examples:

 // Example with US characters only $address = 'john.doe@email.com'; if(filter_var($address, FILTER_VALIDATE_EMAIL)) < echo 'Valid!'; >else < echo 'Not valid :('; >// Example with Unicode characters $address = 'Потапов@email.com'; if(filter_var($address, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE)) < echo 'Valid!'; >else

However, a look at the source code of the filter_var() function on GitHub makes it immediately clear that checking the email address format will not work in all cases. Here is the developer’s comment: This regex does not handle comments and folding whitespace

Indeed, even if rare, whitespaces are allowed in an email address as long as they are enquoted, and the function could, in this case, like other similar cases, provide a false negative (indicating that the email address is not valid, while it is).

Читайте также:  Python pandas dataframe size

Validate emails with PHP’s filter_var() function

However, validating the address format is not enough. For a form data validation script to be effective, it must check if the email address actually exists.

For example, the email address john.doe@donteventrytofindthis.server, or even simpler john.doe@mgail.com, although having a valid format, would not exist. A validation solely based on the filter_var() function would not detect the error.

To implement such a verification script, it would be necessary to write complex logic to test the domain name’s existence, then query its records to determine if the MX fields are correctly filled in, and finally test if the SMTP server responds correctly. As one can easily imagine, this is a heavy task.

The most efficient solution for email verification with PHP: using Abstract API

When it is too difficult to develop an effective solution, one must turn to the services available on the Internet and ideally choose one of the best email validation APIs.

Abstract provides a free API that allows verification of email addresses, validating their format, and checking if the domain name is routable (in other words: it checks if the server exists). The API also indicates whether the email address is from a disposable email service that does not need identification to be used.

To use the Abstract API, create an account and get your private API key. Then using the API is as simple as a call via curl, like this:

 $api_key = 'your_key'; $email = 'john.doe@email.com'; $ch = curl_init('https://emailvalidation.abstractapi.com/v1/?api_key='.$api_key.'&email='.$email); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); $data = curl_exec($ch); curl_close($ch); print_r($data); 

Abstract’s Email Validation API comes with PHP libraries, code snippets, guides, and more.

Источник

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