首页 后端开发 php教程 php实现RFC兼容的电子邮件地址验证

php实现RFC兼容的电子邮件地址验证

Jul 25, 2016 am 08:56 AM

  1. /*
  2. Copyright 2009 Dominic Sayers
  3. (dominic_sayers@hotmail.com)
  4. (http://www.dominicsayers.com)
  5. This source file is subject to the Common Public Attribution License Version 1.0 (CPAL) license.

  6. The license terms are available through the world-wide-web at http://www.opensource.org/licenses/cpal_1.0
  7. */
  8. function is_email ($email, $checkDNS = false) {
  9. // Check that $email is a valid address
  10. // (http://tools.ietf.org/html/rfc3696)
  11. // (http://tools.ietf.org/html/rfc5322#section-3.4.1)
  12. // (http://tools.ietf.org/html/rfc5321#section-4.1.3)
  13. // (http://tools.ietf.org/html/rfc4291#section-2.2)
  14. // (http://tools.ietf.org/html/rfc1123#section-2.1)
  15. // Contemporary email addresses consist of a "local part" separated from
  16. // a "domain part" (a fully-qualified domain name) by an at-sign ("@").
  17. // (http://tools.ietf.org/html/rfc3696#section-3)
  18. $index = strrpos($email,'@');
  19. if ($index === false) return false; // No at-sign

  20. if ($index === 0) return false; // No local part
  21. if ($index > 64) return false; // Local part too long
  22. $localPart = substr($email, 0, $index);

  23. $domain = substr($email, $index + 1);
  24. $domainLength = strlen($domain);
  25. if ($domainLength === 0) return false; // No domain part
  26. if ($domainLength > 255) return false; // Domain part too long
  27. // Let's check the local part for RFC compliance...

  28. //
  29. // Period (".") may...appear, but may not be used to start or end the
  30. // local part, nor may two or more consecutive periods appear.
  31. // (http://tools.ietf.org/html/rfc3696#section-3)
  32. if (preg_match('/^\\.|\\.\\.|\\.$/', $localPart) > 0) return false; // Dots in wrong place
  33. // Any ASCII graphic (printing) character other than the

  34. // at-sign ("@"), backslash, double quote, comma, or square brackets may
  35. // appear without quoting. If any of that list of excluded characters
  36. // are to appear, they must be quoted
  37. // (http://tools.ietf.org/html/rfc3696#section-3)
  38. if (preg_match('/^"(?:.)*"$/', $localPart) > 0) {
  39. // Local part is a quoted string
  40. if (preg_match('/(?:.)+[^\\\\]"(?:.)+/', $localPart) > 0) return false; // Unescaped quote character inside quoted string
  41. } else {
  42. if (preg_match('/[ @\\[\\]\\\\",]/', $localPart) > 0)
  43. // Check all excluded characters are escaped
  44. $stripped = preg_replace('/\\\\[ @\\[\\]\\\\",]/', '', $localPart);
  45. if (preg_match('/[ @\\[\\]\\\\",]/', $stripped) > 0) return false; // Unquoted excluded characters
  46. }
  47. // Now let's check the domain part...

  48. // The domain name can also be replaced by an IP address in square brackets

  49. // (http://tools.ietf.org/html/rfc3696#section-3)
  50. // (http://tools.ietf.org/html/rfc5321#section-4.1.3)
  51. // (http://tools.ietf.org/html/rfc4291#section-2.2)
  52. if (preg_match('/^\\[(.)+]$/', $domain) === 1) {
  53. // It's an address-literal
  54. $addressLiteral = substr($domain, 1, $domainLength - 2);
  55. $matchesIP = array();
  56. // Extract IPv4 part from the end of the address-literal (if there is one)
  57. if (preg_match('/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/', $addressLiteral, $matchesIP) > 0) {
  58. $index = strrpos($addressLiteral, $matchesIP[0]);
  59. if ($index === 0) {
  60. // Nothing there except a valid IPv4 address, so...
  61. return true;
  62. } else {
  63. // Assume it's an attempt at a mixed address (IPv6 + IPv4)
  64. if ($addressLiteral[$index - 1] !== ':') return false; // Character preceding IPv4 address must be ':'
  65. if (substr($addressLiteral, 0, 5) !== 'IPv6:') return false; // RFC5321 section 4.1.3
  66. $IPv6 = substr($addressLiteral, 5, ($index ===7) ? 2 : $index - 6);

  67. $groupMax = 6;
  68. }
  69. } else {
  70. // It must be an attempt at pure IPv6
  71. if (substr($addressLiteral, 0, 5) !== 'IPv6:') return false; // RFC5321 section 4.1.3
  72. $IPv6 = substr($addressLiteral, 5);
  73. $groupMax = 8;
  74. }
  75. $groupCount = preg_match_all('/^[0-9a-fA-F]{0,4}|\\:[0-9a-fA-F]{0,4}|(.)/', $IPv6, $matchesIP);

  76. $index = strpos($IPv6,'::');
  77. if ($index === false) {

  78. // We need exactly the right number of groups
  79. if ($groupCount !== $groupMax) return false; // RFC5321 section 4.1.3
  80. } else {
  81. if ($index !== strrpos($IPv6,'::')) return false; // More than one '::'
  82. $groupMax = ($index === 0 || $index === (strlen($IPv6) - 2)) ? $groupMax : $groupMax - 1;
  83. if ($groupCount > $groupMax) return false; // Too many IPv6 groups in address
  84. }
  85. // Check for unmatched characters

  86. array_multisort($matchesIP[1], SORT_DESC);
  87. if ($matchesIP[1][0] !== '') return false; // Illegal characters in address
  88. // It's a valid IPv6 address, so...

  89. return true;
  90. } else {
  91. // It's a domain name...
  92. // The syntax of a legal Internet host name was specified in RFC-952

  93. // One aspect of host name syntax is hereby changed: the
  94. // restriction on the first character is relaxed to allow either a
  95. // letter or a digit.
  96. // (http://tools.ietf.org/html/rfc1123#section-2.1)
  97. //
  98. // NB RFC 1123 updates RFC 1035, but this is not currently apparent from reading RFC 1035.
  99. //
  100. // Most common applications, including email and the Web, will generally not permit...escaped strings
  101. // (http://tools.ietf.org/html/rfc3696#section-2)
  102. //
  103. // Characters outside the set of alphabetic characters, digits, and hyphen MUST NOT appear in domain name
  104. // labels for SMTP clients or servers
  105. // (http://tools.ietf.org/html/rfc5321#section-4.1.2)
  106. //
  107. // RFC5321 precludes the use of a trailing dot in a domain name for SMTP purposes
  108. // (http://tools.ietf.org/html/rfc5321#section-4.1.2)
  109. $matches = array();
  110. $groupCount = preg_match_all('/(?:[0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]|[a-zA-Z])(?:\\.|$)|(.)/', $domain, $matches);
  111. $level = count($matches[0]);
  112. if ($level == 1) return false; // Mail host can't be a TLD

  113. $TLD = $matches[0][$level - 1];

  114. if (substr($TLD, strlen($TLD) - 1, 1) === '.') return false; // TLD can't end in a dot
  115. if (preg_match('/^[0-9]+$/', $TLD) > 0) return false; // TLD can't be all-numeric
  116. // Check for unmatched characters

  117. array_multisort($matches[1], SORT_DESC);
  118. if ($matches[1][0] !== '') return false; // Illegal characters in domain, or label longer than 63 characters
  119. // Check DNS?

  120. if ($checkDNS && function_exists('checkdnsrr')) {
  121. if (!(checkdnsrr($domain, 'A') || checkdnsrr($domain, 'MX'))) {
  122. return false; // Domain doesn't actually exist
  123. }
  124. }
  125. // Eliminate all other factors, and the one which remains must be the truth.

  126. // (Sherlock Holmes, The Sign of Four)
  127. return true;
  128. }
  129. }
  130. function unitTest ($email, $reason = '') {

  131. $expected = ($reason === '') ? true : false;
  132. $valid = is_email($email);
  133. $not = ($valid) ? '' : ' not';
  134. $unexpected = ($valid !== $expected) ? ' This was unexpected!' : '';
  135. $reason = ($reason === '') ? "" : " Reason: $reason";
  136. return "The address $email is$not valid.$unexpected$reason
    \n";
  137. }
  138. // Email validator test cases (Dominic Sayers, January 2009)

  139. // Valid addresses
  140. echo unitTest('first.last@example.com');
  141. echo unitTest('1234567890123456789012345678901234567890123456789012345678901234@example.com');
  142. echo unitTest('"first last"@example.com');
  143. echo unitTest('"first\\"last"@example.com'); // Not totally sure whether this is valid or not
  144. echo unitTest('first\\@last@example.com');
  145. echo unitTest('"first@last"@example.com');
  146. echo unitTest('first\\\\last@example.com'); // Note that \ is escaped even in single-quote strings, so this is testing "first\\last"@example.com
  147. echo unitTest('first.last@x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.
  148. x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x2345');
  149. echo unitTest('first.last@[12.34.56.78]');
  150. echo unitTest('first.last@[IPv6:::12.34.56.78]');
  151. echo unitTest('first.last@[IPv6:1111:2222:3333::4444:12.34.56.78]');
  152. echo unitTest('first.last@[IPv6:1111:2222:3333:4444:5555:6666:12.34.56.78]');
  153. echo unitTest('first.last@[IPv6:::1111:2222:3333:4444:5555:6666]');
  154. echo unitTest('first.last@[IPv6:1111:2222:3333::4444:5555:6666]');
  155. echo unitTest('first.last@[IPv6:1111:2222:3333:4444:5555:6666::]');
  156. echo unitTest('first.last@[IPv6:1111:2222:3333:4444:5555:6666:7777:8888]');
  157. echo unitTest('first.last@x23456789012345678901234567890123456789012345678901234567890123.example.com');
  158. echo unitTest('first.last@1xample.com');
  159. echo unitTest('first.last@123.example.com');
  160. // Invalid addresses

  161. echo unitTest('first.last', "No @");
  162. echo unitTest('@example.com', "No local part");
  163. echo unitTest('12345678901234567890123456789012345678901234567890123456789012345@example.com', "Local part more than 64 characters");
  164. echo unitTest('.first.last@example.com', "Local part starts with a dot");
  165. echo unitTest('first.last.@example.com', "Local part ends with a dot");
  166. echo unitTest('first..last@example.com', "Local part has consecutive dots");
  167. echo unitTest('"first"last"@example.com', "Local part contains unescaped excluded characters");
  168. echo unitTest('first\\\\@last@example.com', "Local part contains unescaped excluded characters");
  169. echo unitTest('first.last@', "No domain");
  170. echo unitTest('first.last@x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.
  171. x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456789.x23456', "Domain exceeds 255 chars");
  172. echo unitTest('first.last@[.12.34.56.78]', "Only char that can precede IPv4 address is ':'");
  173. echo unitTest('first.last@[12.34.56.789]', "Can't be interpreted as IPv4 so IPv6 tag is missing");
  174. echo unitTest('first.last@[::12.34.56.78]', "IPv6 tag is missing");
  175. echo unitTest('first.last@[IPv5:::12.34.56.78]', "IPv6 tag is wrong");
  176. echo unitTest('first.last@[IPv6:1111:2222:3333::4444:5555:12.34.56.78]', "Too many IPv6 groups (4 max)");
  177. echo unitTest('first.last@[IPv6:1111:2222:3333:4444:5555:12.34.56.78]', "Not enough IPv6 groups");
  178. echo unitTest('first.last@[IPv6:1111:2222:3333:4444:5555:6666:7777:12.34.56.78]', "Too many IPv6 groups (6 max)");
  179. echo unitTest('first.last@[IPv6:1111:2222:3333:4444:5555:6666:7777]', "Not enough IPv6 groups");
  180. echo unitTest('first.last@[IPv6:1111:2222:3333:4444:5555:6666:7777:8888:9999]', "Too many IPv6 groups (8 max)");
  181. echo unitTest('first.last@[IPv6:1111:2222::3333::4444:5555:6666]', "Too many '::' (can be none or one)");
  182. echo unitTest('first.last@[IPv6:1111:2222:3333::4444:5555:6666:7777]', "Too many IPv6 groups (6 max)");
  183. echo unitTest('first.last@[IPv6:1111:2222:333x::4444:5555]', "x is not valid in an IPv6 address");
  184. echo unitTest('first.last@[IPv6:1111:2222:33333::4444:5555]', "33333 is not a valid group in an IPv6 address");
  185. echo unitTest('first.last@example.123', "TLD can't be all digits");
  186. echo unitTest('first.last@com', "Mail host must be second- or lower level");
  187. echo unitTest('first.last@-xample.com', "Label can't begin with a hyphen");
  188. echo unitTest('first.last@exampl-.com', "Label can't end with a hyphen");
  189. echo unitTest('first.last@x234567890123456789012345678901234567890123456789012345678901234.example.com', "Label can't be longer than 63 octets");
  190. // Test cases from RFC3696 (February 2004, http://tools.ietf.org/html/rfc3696#section-3)

  191. echo unitTest('Abc\\@def@example.com');
  192. echo unitTest('Fred\\ Bloggs@example.com');
  193. echo unitTest('Joe.\\\\Blow@example.com');
  194. echo unitTest('"Abc@def"@example.com');
  195. echo unitTest('"Fred Bloggs"@example.com');
  196. echo unitTest('user+mailbox@example.com');
  197. echo unitTest('customer/department=shipping@example.com');
  198. echo unitTest('$A12345@example.com');
  199. echo unitTest('!def!xyz%abc@example.com');
  200. echo unitTest('_somename@example.com');
  201. // Test cases from Doug Lovell (LinuxJournal, June 2007, http://www.linuxjournal.com/article/9585)

  202. echo unitTest("dclo@us.ibm.com");
  203. echo unitTest("abc\\@def@example.com");
  204. echo unitTest("abc\\\\@example.com");
  205. echo unitTest("Fred\\ Bloggs@example.com");
  206. echo unitTest("Joe.\\\\Blow@example.com");
  207. echo unitTest("\"Abc@def\"@example.com");
  208. echo unitTest("\"Fred Bloggs\"@example.com");
  209. echo unitTest("customer/department=shipping@example.com");
  210. echo unitTest("\$A12345@example.com");
  211. echo unitTest("!def!xyz%abc@example.com");
  212. echo unitTest("_somename@example.com");
  213. echo unitTest("user+mailbox@example.com");
  214. echo unitTest("peter.piper@example.com");
  215. echo unitTest("Doug\\ \\\"Ace\\\"\\ Lovell@example.com");
  216. echo unitTest("\"Doug \\\"Ace\\\" L.\"@example.com");
  217. echo unitTest("abc@def@example.com", "Doug Lovell says this should fail");
  218. echo unitTest("abc\\\\@def@example.com", "Doug Lovell says this should fail");
  219. echo unitTest("abc\\@example.com", "Doug Lovell says this should fail");
  220. echo unitTest("@example.com", "Doug Lovell says this should fail");
  221. echo unitTest("doug@", "Doug Lovell says this should fail");
  222. echo unitTest("\"qu@example.com", "Doug Lovell says this should fail");
  223. echo unitTest("ote\"@example.com", "Doug Lovell says this should fail");
  224. echo unitTest(".dot@example.com", "Doug Lovell says this should fail");
  225. echo unitTest("dot.@example.com", "Doug Lovell says this should fail");
  226. echo unitTest("two..dot@example.com", "Doug Lovell says this should fail");
  227. echo unitTest("\"Doug \"Ace\" L.\"@example.com", "Doug Lovell says this should fail");
  228. echo unitTest("Doug\\ \\\"Ace\\\"\\ L\\.@example.com", "Doug Lovell says this should fail");
  229. echo unitTest("hello world@example.com", "Doug Lovell says this should fail");
  230. echo unitTest("gatsby@f.sc.ot.t.f.i.tzg.era.l.d.", "Doug Lovell says this should fail");
  231. ?>
复制代码


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1655
14
CakePHP 教程
1413
52
Laravel 教程
1306
25
PHP教程
1252
29
C# 教程
1226
24
在PHP API中说明JSON Web令牌(JWT)及其用例。 在PHP API中说明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息,主要用于身份验证和信息交换。1.JWT由Header、Payload和Signature三部分组成。2.JWT的工作原理包括生成JWT、验证JWT和解析Payload三个步骤。3.在PHP中使用JWT进行身份验证时,可以生成和验证JWT,并在高级用法中包含用户角色和权限信息。4.常见错误包括签名验证失败、令牌过期和Payload过大,调试技巧包括使用调试工具和日志记录。5.性能优化和最佳实践包括使用合适的签名算法、合理设置有效期、

会话如何劫持工作,如何在PHP中减轻它? 会话如何劫持工作,如何在PHP中减轻它? Apr 06, 2025 am 12:02 AM

会话劫持可以通过以下步骤实现:1.获取会话ID,2.使用会话ID,3.保持会话活跃。在PHP中防范会话劫持的方法包括:1.使用session_regenerate_id()函数重新生成会话ID,2.通过数据库存储会话数据,3.确保所有会话数据通过HTTPS传输。

什么是REST API设计原理? 什么是REST API设计原理? Apr 04, 2025 am 12:01 AM

RESTAPI设计原则包括资源定义、URI设计、HTTP方法使用、状态码使用、版本控制和HATEOAS。1.资源应使用名词表示并保持层次结构。2.HTTP方法应符合其语义,如GET用于获取资源。3.状态码应正确使用,如404表示资源不存在。4.版本控制可通过URI或头部实现。5.HATEOAS通过响应中的链接引导客户端操作。

您如何在PHP中有效处理异常(尝试,捕捉,最后,投掷)? 您如何在PHP中有效处理异常(尝试,捕捉,最后,投掷)? Apr 05, 2025 am 12:03 AM

在PHP中,异常处理通过try,catch,finally,和throw关键字实现。1)try块包围可能抛出异常的代码;2)catch块处理异常;3)finally块确保代码始终执行;4)throw用于手动抛出异常。这些机制帮助提升代码的健壮性和可维护性。

PHP中的匿名类是什么?您何时可以使用它们? PHP中的匿名类是什么?您何时可以使用它们? Apr 04, 2025 am 12:02 AM

匿名类在PHP中的主要作用是创建一次性使用的对象。1.匿名类允许在代码中直接定义没有名字的类,适用于临时需求。2.它们可以继承类或实现接口,增加灵活性。3.使用时需注意性能和代码可读性,避免重复定义相同的匿名类。

包括,require,incement_once,require_once之间有什么区别? 包括,require,incement_once,require_once之间有什么区别? Apr 05, 2025 am 12:07 AM

在PHP中,include,require,include_once,require_once的区别在于:1)include产生警告并继续执行,2)require产生致命错误并停止执行,3)include_once和require_once防止重复包含。这些函数的选择取决于文件的重要性和是否需要防止重复包含,合理使用可以提高代码的可读性和可维护性。

说明PHP中的不同错误类型(注意,警告,致命错误,解析错误)。 说明PHP中的不同错误类型(注意,警告,致命错误,解析错误)。 Apr 08, 2025 am 12:03 AM

PHP中有四种主要错误类型:1.Notice:最轻微,不会中断程序,如访问未定义变量;2.Warning:比Notice严重,不会终止程序,如包含不存在文件;3.FatalError:最严重,会终止程序,如调用不存在函数;4.ParseError:语法错误,会阻止程序执行,如忘记添加结束标签。

PHP和Python:比较两种流行的编程语言 PHP和Python:比较两种流行的编程语言 Apr 14, 2025 am 12:13 AM

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

See all articles