Php 简明教程

PHP - Form Email/URL

PHP 为验证表单数据项(它们是字符串,但预期是电子邮件 ID 或 URL 的表示)提供了两种选择。检查表单元素是否包含电子邮件/URL 的一种方法是使用 RegEx (regular expressions) ,另一种更方便的方法是使用 filter_var() 函数。让我们应用这两种方法,并验证由表单提交给 PHP 脚本的电子邮件和 URL。

PHP provides two alternatives for validating the form data items which are strings but are expected to be a representation of Email ID or a URL. One way to check the form element contains email/URL is with the use of RegEx (regular expressions), and the other, more convenient approach is to use filter_var() function. Let us apply both these methods and validate email and URL submitted by a form to a PHP script.

本章中使用的 HTML 表单如下 −

The HTML Form used for this chapter is as follows −

<h1>Email and URL Validation</h1>
<form action="hello.php" method="POST">
   <p><label for="email">Enter your email:</label>
   <input type="text" id="email" name="email"></p>
   <p><label for="URL">Enter your website<label>
   <input type = "text" id="URL" name="url"></p>
   <input type="submit">
</form>

Validation with Regex

PHP 的内置函数库包括执行正则表达式匹配的 preg_match() function

PHP’s built-in function library includes the preg_match() function that performs a regular expression match.

preg_match(
   string $pattern,
   string $subject,
   array &$matches = null,
   int $flags = 0,
   int $offset = 0
): int|false

此函数在 subject 中搜索与 pattern 中给出的正则表达式匹配的部分。如果 pattern 与给定的 subject 匹配, preg_match() 返回 1;如果它不匹配,则返回 0;如果失败,则返回 false

This function searches subject for a match to the regular expression given in pattern. preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or false on failure.

有效的电子邮件 ID 应满足以下正则表达式 −

A valid email ID should satisfy the following regular expression −

"/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix"

同样,有效的 URL 应满足以下正则表达式 −

Similarly, a valid URL should satisfy the following regular expression −

"/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i"

如果字符串是有效的电子邮件 ID,则以下函数返回“1”或“0”。

The following function returns "1" or "0" if the string is a valid email ID.

function checkemail($str) {
   return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}

Example

让我们使用 checkmail() function ,借助以下 PHP 代码,来检查上面 HTML 中的电子邮件字段是否有效 −

Let us use the checkmail() function to check whether the email field in the above HTML is valid or not, with the help of following PHP code −

<?php
   function checkemail($str) {
      return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@
         ([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
   }
   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $email = $_POST['email'];
      if(!checkemail($email)){
         echo "Invalid email address.";
      } else {
         echo "Valid email address.";
      }
   }
?>

HTML 表单如下呈现 −

The HTML form is rendered as below −

php form email url

通过在电子邮件字段中输入有效/无效的电子邮件字符串来测试 PHP 代码。

Test the PHP code by entering valid/invalid email string in the email field.

以下 checkURL() function 检查字符串是否表示有效的 URL 或无效的 URL,并返回“1 或“0”。

The following checkURL() function checks if a string represents a valid or invalid URL, and returns "1 or "0".

function checkURL($str) {
   return (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)
      [-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $str)) ? FALSE : TRUE;
}

Example

从 $_POST 数组中提取的 URL 字段作为参数提供给上述函数。

The URL field extracted from the $_POST array is given as argument to the above function.

<?php
   function checkURL($str) {
      return (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]
         *[-a-z0-9+&@#\/%=~_|]/i", $str)) ? FALSE : TRUE;
   }
   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $url = $_POST['url'];
      if(!checkURL($url)){
         echo "Invalid URL.";
      } else {
         echo "Valid URL.";
      }
   }
?>

您可以通过在上面表单的 URL 字段中输入 URL 字符串来测试上面的代码。

You can test the above code by entering URL string in the URL field of the above form.

Using filter_var() function

内置的 filter_var() 函数使用指定的过滤器过滤变量。

The built-in filter_var() function filters a variable with a specified filter.

filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed

根据 $filter 参数的值作为枚举过滤器 ID,将检查 $value 参数,如果过滤器失败,则该函数返回过滤后的数据或 false。

Depending on the enumerated filter ID as the value of $filter parameter, the $value parameter is checked and the function returns the filtered data, or false if the filter fails.

有各种 predefined filter ID constants 可用 −

There are various predefined filter ID constants available −

Sr.No

ID & Description

1

FILTER_VALIDATE_BOOL Returns true for "1", "true", "on" and "yes". Returns false otherwise.

2

FILTER_VALIDATE_DOMAIN Validates whether the domain name label lengths are valid.

3

FILTER_VALIDATE_EMAIL Validates whether the value is a valid e-mail address.

4

FILTER_VALIDATE_IP Validates value as IP address

5

FILTER_VALIDATE_URL Validates value as URL

Example

以下 PHP 脚本验证了以上 HTML 提交的电子邮件和 URL 数据 −

The following PHP script validates the email and URL data submitted by the HTML for above −

<?php
   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $email = $_POST['email'];
      $url = $_POST['url'];

      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
         echo "Invalid email format and please re-enter valid email\n";
      }
      else
      echo "Email entered is in valid format\n";

      if (!filter_var($url, FILTER_VALIDATE_URL)) {
         echo "Invalid URL format and please re-enter valid URL\n";
      }
      else
      echo "URL entered is in valid format\n";
   }
?>

你可以通过输入有效的/无效的电子邮件/URL 来测试以上脚本的性能。

You can test the performance of the above script by entering valid/invalid email/URL.