php 郵件驗證
Suppose there is a form floating where every user has to fill his/her email ID. It might happen that due to typing error or any other problem user doesn't fill his/her mail ID correctly. Then at that point, the program should be such that it should print a user-friendly message notifying the user that address filled is wrong. This is a simple program and can be done in two ways in PHP language.
假設有一個浮動的表單,每個用戶都必須填寫他/她的電子郵件ID。 由于鍵入錯誤或其他任何問題,用戶可能無法正確填寫其郵件ID。 然后,在那時,程序應該是這樣的:它應該打印一條用戶友好的消息,通知用戶地址填寫錯誤。 這是一個簡單的程序,可以用PHP語言以兩種方式完成。
Method 1: Naive approach
方法1:天真的方法
There is a filter called FILTER_VALIDATE_EMAIL which is in-built in PHP and validates mail ID.
有一個名為FILTER_VALIDATE_EMAIL的過濾器,該過濾器是PHP內置的,可驗證郵件ID。
The function filter_var() is also used in this program which takes two arguments. The first is the user mail ID and the second is the email filter. The function will return a Boolean answer according to which we can print the message of our desire.
此程序中也使用了filter_var()函數,該函數接受兩個參數。 第一個是用戶郵件ID,第二個是電子郵件過濾器。 該函數將返回一個布爾值答案,根據該答案我們可以打印所需的消息。
Program:
程序:
<?php
$email = "[email?protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo '"' . $email . ' " is valid'."\n";
}
else {
echo '"' . $email . ' " is Invalid'."\n";
}
$email = "inf at includehelp.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo '"' . $email . ' " is valid'."\n";
}
else {
echo '"' . $email . ' " is Invalid'."\n";
}
?>
Output:
輸出:
"[email?protected] " is valid
"inf at includehelp.com " is Invalid
Method 2: Separating strings
方法2:分隔字符串
How a normal human being validates some email addresses? The human observes some pattern in the string as well as some special characters while checking the validation of an email. The same can be done through programming. An email ID should necessarily have the character '@' and a string '.com' in a specific order. A function called preg_match() will be used for checking this order and characters.
普通人如何驗證某些電子郵件地址? 人們在檢查電子郵件的有效性時會觀察到字符串中的某些模式以及一些特殊字符。 可以通過編程完成相同的操作。 電子郵件ID必須按特定順序包含字符“ @”和字符串“ .com” 。 稱為preg_match()的函數將用于檢查此順序和字符。
<?php
// A functios is created for checking validity of mail
function mail_validation($str) {
return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
// Taking user input of email ID
$a=readline('Input an email address: ');
if(!mail_validation($a))
{
echo "Invalid email address.";
}
else{
echo "Valid email address.";
}
?>
Output:
輸出:
RUN 1:
Input an email address: [email?protected]
Valid email address.
RUN 2:
Input an email address: [email?protected]
Invalid email address.
翻譯自: https://www.includehelp.com/php/program-to-validate-an-email.aspx
php 郵件驗證