suchen
HeimBackend-EntwicklungPHP-Tutorialphp实现RFC兼容的电子邮件地址验证

  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. ?>
复制代码


Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
PHP und Python: Verschiedene Paradigmen erklärtPHP und Python: Verschiedene Paradigmen erklärtApr 18, 2025 am 12:26 AM

PHP ist hauptsächlich prozedurale Programmierung, unterstützt aber auch die objektorientierte Programmierung (OOP). Python unterstützt eine Vielzahl von Paradigmen, einschließlich OOP, funktionaler und prozeduraler Programmierung. PHP ist für die Webentwicklung geeignet, und Python eignet sich für eine Vielzahl von Anwendungen wie Datenanalyse und maschinelles Lernen.

PHP und Python: Ein tiefes Eintauchen in ihre GeschichtePHP und Python: Ein tiefes Eintauchen in ihre GeschichteApr 18, 2025 am 12:25 AM

PHP entstand 1994 und wurde von Rasmuslerdorf entwickelt. Es wurde ursprünglich verwendet, um Website-Besucher zu verfolgen und sich nach und nach zu einer serverseitigen Skriptsprache entwickelt und in der Webentwicklung häufig verwendet. Python wurde Ende der 1980er Jahre von Guidovan Rossum entwickelt und erstmals 1991 veröffentlicht. Es betont die Lesbarkeit und Einfachheit der Code und ist für wissenschaftliche Computer, Datenanalysen und andere Bereiche geeignet.

Wählen Sie zwischen PHP und Python: Ein LeitfadenWählen Sie zwischen PHP und Python: Ein LeitfadenApr 18, 2025 am 12:24 AM

PHP eignet sich für Webentwicklung und schnelles Prototyping, und Python eignet sich für Datenwissenschaft und maschinelles Lernen. 1.PHP wird für die dynamische Webentwicklung verwendet, mit einfacher Syntax und für schnelle Entwicklung geeignet. 2. Python hat eine kurze Syntax, ist für mehrere Felder geeignet und ein starkes Bibliotheksökosystem.

PHP und Frameworks: Modernisierung der SprachePHP und Frameworks: Modernisierung der SpracheApr 18, 2025 am 12:14 AM

PHP bleibt im Modernisierungsprozess wichtig, da es eine große Anzahl von Websites und Anwendungen unterstützt und sich den Entwicklungsbedürfnissen durch Frameworks anpasst. 1.PHP7 verbessert die Leistung und führt neue Funktionen ein. 2. Moderne Frameworks wie Laravel, Symfony und Codesigniter vereinfachen die Entwicklung und verbessern die Codequalität. 3.. Leistungsoptimierung und Best Practices verbessern die Anwendungseffizienz weiter.

Auswirkungen von PHP: Webentwicklung und darüber hinausAuswirkungen von PHP: Webentwicklung und darüber hinausApr 18, 2025 am 12:10 AM

PhPhas significantantyPactedWebDevelopmentAndendendsbeyondit.1) iTpowersMAjorPlatforms-LikewordpressandExcelsInDatabaseInteractions.2) php'SadaptabilityAllowStoscaleForLargeApplicationsfraMe-Linien-Linien-Linien-Linienkripte

Wie funktioniert der Php -Typ -Hinweis, einschließlich Skalartypen, Rückgabetypen, Gewerkschaftstypen und nullbaren Typen?Wie funktioniert der Php -Typ -Hinweis, einschließlich Skalartypen, Rückgabetypen, Gewerkschaftstypen und nullbaren Typen?Apr 17, 2025 am 12:25 AM

PHP -Typ -Eingabeaufforderungen zur Verbesserung der Codequalität und der Lesbarkeit. 1) Tipps zum Skalartyp: Da Php7.0 in den Funktionsparametern wie int, float usw. angegeben werden dürfen. 3) Eingabeaufforderung für Gewerkschaftstyp: Da Php8.0 in Funktionsparametern oder Rückgabetypen angegeben werden dürfen. 4) Nullierstyp Eingabeaufforderung: Ermöglicht die Einbeziehung von Nullwerten und Handlungsfunktionen, die Nullwerte zurückgeben können.

Wie handelt es sich bei PHP -Objektklonen (Klonschlüsselwort) und der __clone Magic -Methode?Wie handelt es sich bei PHP -Objektklonen (Klonschlüsselwort) und der __clone Magic -Methode?Apr 17, 2025 am 12:24 AM

Verwenden Sie in PHP das Klonschlüsselwort, um eine Kopie des Objekts zu erstellen und das Klonierungsverhalten über die \ _ \ _ Clone Magic -Methode anzupassen. 1. Verwenden Sie das Klonschlüsselwort, um eine flache Kopie zu erstellen und die Eigenschaften des Objekts, nicht die Eigenschaften des Objekts zu klonen. 2. Die \ _ \ _ Klonmethode kann verschachtelte Objekte tief kopieren, um flache Kopierprobleme zu vermeiden. 3. achten Sie darauf, dass kreisförmige Referenzen und Leistungsprobleme beim Klonen vermieden werden, und optimieren Sie die Klonierungsvorgänge, um die Effizienz zu verbessern.

PHP vs. Python: Anwendungsfälle und AnwendungenPHP vs. Python: Anwendungsfälle und AnwendungenApr 17, 2025 am 12:23 AM

PHP eignet sich für Webentwicklungs- und Content -Management -Systeme, und Python eignet sich für Datenwissenschafts-, maschinelles Lernen- und Automatisierungsskripte. 1.PHP hat eine gute Leistung beim Erstellen von schnellen und skalierbaren Websites und Anwendungen und wird üblicherweise in CMS wie WordPress verwendet. 2. Python hat sich in den Bereichen Datenwissenschaft und maschinelles Lernen mit reichen Bibliotheken wie Numpy und TensorFlow übertrifft.

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

R.E.P.O. Energiekristalle erklärten und was sie tun (gelber Kristall)
1 Monate vorBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Beste grafische Einstellungen
1 Monate vorBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Crossplay haben?
1 Monate vorBy尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

WebStorm-Mac-Version

WebStorm-Mac-Version

Nützliche JavaScript-Entwicklungstools

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

Herunterladen der Mac-Version des Atom-Editors

Herunterladen der Mac-Version des Atom-Editors

Der beliebteste Open-Source-Editor

SecLists

SecLists

SecLists ist der ultimative Begleiter für Sicherheitstester. Dabei handelt es sich um eine Sammlung verschiedener Arten von Listen, die häufig bei Sicherheitsbewertungen verwendet werden, an einem Ort. SecLists trägt dazu bei, Sicherheitstests effizienter und produktiver zu gestalten, indem es bequem alle Listen bereitstellt, die ein Sicherheitstester benötigen könnte. Zu den Listentypen gehören Benutzernamen, Passwörter, URLs, Fuzzing-Payloads, Muster für vertrauliche Daten, Web-Shells und mehr. Der Tester kann dieses Repository einfach auf einen neuen Testcomputer übertragen und hat dann Zugriff auf alle Arten von Listen, die er benötigt.

SAP NetWeaver Server-Adapter für Eclipse

SAP NetWeaver Server-Adapter für Eclipse

Integrieren Sie Eclipse mit dem SAP NetWeaver-Anwendungsserver.