Home Backend Development PHP Tutorial Verify email in PHP

Verify email in PHP

Feb 28, 2024 am 10:31 AM
php programming Backend Development php written

Validating emails in PHP is one of the common needs in website development. Effective email verification improves user input accuracy and prevents malicious registrations and information leakage. This article will introduce how to use PHP to write simple and effective email verification code to ensure that the email format entered by the user conforms to the specification. Through the guidance of this article, you can easily implement the email verification function and improve the user experience and security of your website. PHP editor Apple will explain the method of verifying emails in detail, allowing you to easily master the skills.

We will also demonstrate another way to validate emails in php using FILTER_SANITIZE_EMAIL and FILTER_VALIDATE_EMAIL filter name IDs and the fiter_var() function Address method. This method first cleans the email address and then verifies the email address.

We'll cover another way to validate emails in PHP using Regular Expressions. This method uses the preg_match() function to check whether the email is valid based on the provided regular expression.


Validate email in PHP using filter_var() function and FILTER_VALIDATE_EMAIL

We can use the

filter_var() function to filter variables with a specific filter name. FILTER_VALIDATE_EMAIL Filter name specifies an email that requires validation. This function takes the email address as a string as the first argument and the filter ID specified above as the second argument. So we can check if the email provided is valid. If the function succeeds or returns false, the function returns the filtered data. Email is said to be valid, not that email exists. The filter id validates the email based on the syntax in RFC 822. We can test the verification of the email using valid and invalid emails.

For example, create a function

validateEmail() that accepts a parameter $email. Use the filter_var() function on the $email variable, specifying the filter ID FILTER_VALIDATE_EMAIL as the second parameter. Apply if-else conditions to the filter_var() function. In the if block, show the message saying the email is valid, and in the else condition, show the email is invalid. Outside the function, call the function twice. Provide arguments in the first function call, peter.piper@iana.org and first.last@example.123 on the second call.

We can assume that the email address provided in the example is accessed from the form using the

$_POST variable. The function in the example below is called twice. The first call passes a valid email address, the second an invalid email. The second email address is invalid because it contains a number from the top-level domain. The results are obvious.

Sample code:

<code>
<code class="php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#408080;font-style:italic">#php 7.x
</span></span></span><span style="display:flex;"><span><span style="color:#666"><?</span>php
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">funct<strong class="keylink">io</strong>n</span> <span style="color:#00f">validateEmail</span>(<span style="color:#19177c">$email</span>) {
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">if</span>(filter_var(<span style="color:#19177c">$email</span>, FILTER_VALIDATE_EMAIL)) {
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"</span><span style="color:#b68;font-weight:bold">{</span><span style="color:#19177c">$email</span><span style="color:#b68;font-weight:bold">}</span><span style="color:#ba2121">: A valid email"</span><span style="color:#666">.</span><span style="color:#ba2121">"<br>"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">else</span> {
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"</span><span style="color:#b68;font-weight:bold">{</span><span style="color:#19177c">$email</span><span style="color:#b68;font-weight:bold">}</span><span style="color:#ba2121">: Not a valid email"</span><span style="color:#666">.</span><span style="color:#ba2121">"<br>"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>validateEmail(<span style="color:#ba2121">'peter.piper@iana.org'</span>);
</span></span><span style="display:flex;"><span>validateEmail(<span style="color:#ba2121">'first.last@example.123'</span>);
</span></span><span style="display:flex;"><span><span style="color:#bc7a00">?></span><span >
</span></span></span></code></code>
Copy after login
Output:

<code>
<code class="php hljs" data-lang="php"><span style="display:flex;"><span>phppeter<span style="color:#666">.</span>piper<span style="color:#666">@</span>iana<span style="color:#666">.</span>org<span style="color:#666">:</span> A valid email 
</span></span><span style="display:flex;"><span>first<span style="color:#666">.</span>last<span style="color:#666">@</span>example<span style="color:#666">.</span><span style="color:#666">123</span><span style="color:#666">:</span><span style="color:#008000;font-weight:bold">Not</span> a valid email
</span></span></code></code>
Copy after login

Validating emails in PHP using the

FILTER_VALIDATE_EMAIL, FILTER_SANITIZE_EMAIL and filter_var() functions

We can remove all illegal characters from email address using appended

FILTER_SANITIZE_EMAIL filter name id in first method. The filter name id is the second parameter in the filter_var() function where the email address is the first parameter. This function returns the sanitized email. We can use this feature again to check the validity of the sanitized email address. For this we can follow the first approach using FILTER_VALIDATE_EMAIL filter name id.

For example, create a variable

$email and store an email address that contains illegal characters. Store the email ram(.mugu)@exa//mple.org as a string in a variable. Use the filter_var() function on a variable and use the FILTER_SANITIZE_EMAIL id as the second parameter. Store the function in the same $email variable. Then, apply the if-else statement like the first method. This time, use FILTER_VALIDATE_EMAIL email as the filter name in the function. Likewise, the message is displayed.

In the example below an email address with illegal characters is taken, the

filter_var() function filters these characters and sanitizes the provided email. The email address provided in the example contains illegal characters, such as () and //. The function first removes these characters from the email and then validates the email.

Sample code:

<code>
<code class="php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#408080;font-style:italic">#php 7.x
</span></span></span><span style="display:flex;"><span><span style="color:#666"><?</span>php
</span></span><span style="display:flex;"><span><span style="color:#19177c">$email</span> <span style="color:#666">=</span> <span style="color:#ba2121">"ram(.mugu)@exa//mple.org"</span>;
</span></span><span style="display:flex;"><span><span style="color:#19177c">$email</span> <span style="color:#666">=</span> filter_var(<span style="color:#19177c">$email</span>, FILTER_SANITIZE_EMAIL);
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">if</span>(filter_var(<span style="color:#19177c">$email</span>, FILTER_VALIDATE_EMAIL)) {
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"</span><span style="color:#b68;font-weight:bold">{</span><span style="color:#19177c">$email</span><span style="color:#b68;font-weight:bold">}</span><span style="color:#ba2121">: A valid email"</span><span style="color:#666">.</span><span style="color:#ba2121">"<br>"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">else</span>{
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"</span><span style="color:#b68;font-weight:bold">{</span><span style="color:#19177c">$email</span><span style="color:#b68;font-weight:bold">}</span><span style="color:#ba2121">:Not a valid email"</span><span style="color:#666">.</span><span style="color:#ba2121">"<br>"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#bc7a00">?></span><span >
</span></span></span></code></code>
Copy after login
Output:

<code>
<code class="php hljs" data-lang="php"><span style="display:flex;"><span>ram<span style="color:#666">.</span>mugu<span style="color:#666">@</span>example<span style="color:#666">.</span>org<span style="color:#666">:</span> A valid email
</span></span></code></code>
Copy after login

使用 preg_match() 函数根据正则表达式验证电子邮件

我们可以使用 preg_match() 函数来验证 PHP 中的电子邮件地址。此方法使用正则表达式作为电子邮件的验证规则。我们可以自己创建正则表达式并定义有效电子邮件的规则。preg_match() 函数接受两个参数,其中第一个是正则表达式,第二个是要检查的电子邮件。我们可以使用三元运算符和函数一起检查电子邮件的有效性。

例如,创建两个变量 $email_first$email_secon,并在这些变量中存储两个电子邮件地址。首先存储有效的电子邮件 firstlast11@gmail.com,然后存储无效的电子邮件 firstlast@11gmail,com。编写一个带有一个参数的函数 validateEmail()。命名参数 $email。在函数内部,在 $regex 变量中编写一个正则表达式,如示例代码所示。然后编写一个三元运算符,其中要检查的条件是 preg_match() 函数。将 $regex 作为第一个参数,将 $email 作为第二个参数。当条件为真时打印电子邮件有效的消息,当条件为假时打印电子邮件无效的消息。回显整个三元表达式。在函数外,调用 validateEmail() 函数两次。在第一个函数调用中使用 $email_first 变量,在第二个函数调用中使用 $email_second 变量。

在下面的示例中,我们编写了一个正则表达式,用于创建验证电子邮件的规则。有效的电子邮件包含收件人姓名、@ 符号、域和顶级域。上面创建的正则表达式接受收件人姓名作为字母数字值。字母表由大写字母和小写字母组成。它也接受一个句点。电子邮件必须有 @ 符号。该域仅包含字母。然后电子邮件应该有一个句点。顶级域应该只由字母组成,并且长度应该是两个或三个。正则表达式是基于此规则创建的。第一封电子邮件是有效的,因为它满足所有规则,但第二封电子邮件无效。无效,因为域名中有数字,顶级域名前没有句号。

示例代码:

<code>
<code class="php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#408080;font-style:italic"># php 7.x
</span></span></span><span style="display:flex;"><span><span style="color:#666"><?</span>php
</span></span><span style="display:flex;"><span><span style="color:#19177c">$email_first</span> <span style="color:#666">=</span> <span style="color:#ba2121">'firstlast11@gmail.com'</span>;
</span></span><span style="display:flex;"><span><span style="color:#19177c">$email_second</span> <span style="color:#666">=</span><span style="color:#ba2121">'firstlast@11gmail,com'</span>;
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">function</span> <span style="color:#00f">validateEmail</span>(<span style="color:#19177c">$email</span>) {
</span></span><span style="display:flex;"><span><span style="color:#19177c">$regex</span> <span style="color:#666">=</span> <span style="color:#ba2121">"/^([a-zA-Z0-9\.]+@+[a-zA-Z]+(\.)+[a-zA-Z]{2,3})$/"</span>;
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> preg_match(<span style="color:#19177c">$regex</span>, <span style="color:#19177c">$email</span>) <span style="color:#666">?</span> <span style="color:#ba2121">"The email is valid"</span><span style="color:#666">.</span><span style="color:#ba2121">"<br>"</span> <span style="color:#666">:</span><span style="color:#ba2121">"The email is not valid"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>validateEmail(<span style="color:#19177c">$email_first</span>);
</span></span><span style="display:flex;"><span>validateEmail(<span style="color:#19177c">$email_second</span>);
</span></span><span style="display:flex;"><span><span style="color:#bc7a00">?></span><span >
</span></span></span></code></code>
Copy after login

输出:

<code>
<code class="text hljs" data-lang="text"><span style="display:flex;"><span>The email is valid 
</span></span><span style="display:flex;"><span>The email is not valid
</span></span></code></code>
Copy after login

The above is the detailed content of Verify email in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP format rows to CSV and write file pointer PHP format rows to CSV and write file pointer Mar 22, 2024 am 09:00 AM

This article will explain in detail how PHP formats rows into CSV and writes file pointers. I think it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Format rows to CSV and write to file pointer Step 1: Open file pointer $file=fopen(&quot;path/to/file.csv&quot;,&quot;w&quot;); Step 2: Convert rows to CSV string using fputcsv( ) function converts rows to CSV strings. The function accepts the following parameters: $file: file pointer $fields: CSV fields as an array $delimiter: field delimiter (optional) $enclosure: field quotes (

PHP changes current umask PHP changes current umask Mar 22, 2024 am 08:41 AM

This article will explain in detail about changing the current umask in PHP. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Overview of PHP changing current umask umask is a php function used to set the default file permissions for newly created files and directories. It accepts one argument, which is an octal number representing the permission to block. For example, to prevent write permission on newly created files, you would use 002. Methods of changing umask There are two ways to change the current umask in PHP: Using the umask() function: The umask() function directly changes the current umask. Its syntax is: intumas

PHP calculates MD5 hash of file PHP calculates MD5 hash of file Mar 21, 2024 pm 01:42 PM

This article will explain in detail about PHP calculating the MD5 hash of files. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP calculates the MD5 hash of a file MD5 (MessageDigest5) is a one-way encryption algorithm that converts messages of arbitrary length into a fixed-length 128-bit hash value. It is widely used to ensure file integrity, verify data authenticity and create digital signatures. Calculating the MD5 hash of a file in PHP PHP provides multiple methods to calculate the MD5 hash of a file: Use the md5_file() function. The md5_file() function directly calculates the MD5 hash value of the file and returns a 32-character

PHP returns an array with key values ​​flipped PHP returns an array with key values ​​flipped Mar 21, 2024 pm 02:10 PM

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values ​​in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values ​​swapped. $original_array=[

PHP determines whether a specified key exists in an array PHP determines whether a specified key exists in an array Mar 21, 2024 pm 09:21 PM

This article will explain in detail how PHP determines whether a specified key exists in an array. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP determines whether a specified key exists in an array: In PHP, there are many ways to determine whether a specified key exists in an array: 1. Use the isset() function: isset($array[&quot;key&quot;]) This function returns a Boolean value, true if the specified key exists, false otherwise. 2. Use array_key_exists() function: array_key_exists(&quot;key&quot;,$arr

How to use PHP to determine the number of digits in a number? How to use PHP to determine the number of digits in a number? Mar 26, 2024 am 11:39 AM

A practical method to use PHP to determine how many digits a number has. In programming, there is often a need to determine how many digits a number has. When writing a program in PHP, you can use some simple but practical methods to determine the number of digits in a number. Below we will introduce some methods of using PHP to determine the number of digits in a number, and attach specific code examples. Method 1: Use the strlen function The strlen function in PHP can return the length of a string. If we first convert the number to a string and then use s

PHP returns the numeric encoding of the error message in the previous MySQL operation PHP returns the numeric encoding of the error message in the previous MySQL operation Mar 22, 2024 pm 12:31 PM

This article will explain in detail the numerical encoding of the error message returned by PHP in the previous Mysql operation. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. . Using PHP to return MySQL error information Numeric Encoding Introduction When processing mysql queries, you may encounter errors. In order to handle these errors effectively, it is crucial to understand the numerical encoding of error messages. This article will guide you to use php to obtain the numerical encoding of Mysql error messages. Method of obtaining the numerical encoding of error information 1. mysqli_errno() The mysqli_errno() function returns the most recent error number of the current MySQL connection. The syntax is as follows: $erro

PHP get pi PHP get pi Mar 21, 2024 pm 01:52 PM

This article will explain in detail about obtaining pi in PHP. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Introduction to Obtaining Pi with PHP Pi (π) is the ratio of the circumference to the diameter of a circle. It is an irrational number and cannot be expressed with a finite number of digits. In php, you can use the built-in function M_PI to get an approximate value of pi. M_PI function The M_PI function returns an approximate value of pi, accurate to 14 decimal places. It is a constant of PHP, so you don't need to use any parameters to use it. Syntax output 3.14159265358979 Alternative methods In addition to the M_PI function, there are some alternatives

See all articles