[英]How to read the domain name of an email address input via a form
我有一個登錄表單,我希望能夠提取電子郵件地址輸入的域名,然后用剛剛讀取的新變量覆蓋預定義的變量。
這是我的代碼:
<form action="example.php" method="POST">
<input type="text" name="input_value"> //assume I input gooogle@gmail.com
<input type="hidden" name="isp" id="isp" value="unknown" />
<input type="submit" name="submit">
例子.php:
<?php
$isp = $_POST["isp"];
//rest of code
?>
我希望能夠讀取域並將變量 $isp 轉換為我設置的預定義值,例如 'gmail.com' = 'gmail',因此$isp = 'gmail'
。
您確實應該依賴使用c-client
API 的php-imap模塊中的imap_rfc822_parse_adrlist
。 它處理一個逗號分隔的列表並返回一個對象數組並允許格式User <user@example.com
。 通過一些額外的邏輯,您可以滿足您的需求。
您在評論中表示您不想依賴安裝依賴項。 我強烈建議這樣做,即使有filter_var
函數也提供電子郵件過濾器。 它沒有很好地實施,產生假陰性。 我什至不會依賴它,希望它不會產生誤報。
例如,RFC 822 允許帶引號的字符串出現在郵箱部分。 imap_rfc822_parse_adrlist
和filter_var
認為"abc.def@ghi.jkl"@example.com
和abc."def@ghi".jkl@example.com
是有效的。 但是, abc.def"@"ghi.jkl@example.com
根據 RFC 882 規范也有效,但是filter_var
的假陰性。 IDN 域也存在問題,可能還有更多問題。
在 PHP 中實現完全符合 RFC 822 的正則表達式或算法是一項非常困難且容易出錯的任務。 即使是簡單的電子郵件格式也不應該通過正則表達式或類似的方式進行驗證,因為這將成為錯誤的根源,甚至有一天會成為大型項目中嚴重安全問題的根源。
我可以為您提供一些依靠 filter_var 的后備方案。 同樣,我強烈建議不要默認啟用它。 您可以提供警告以啟用它,風險自負。
<?php declare (strict_types=1);
// This should NOT be enabled. If possible, ensure to have installed the php-imap module.
//
// define('ALLOW_FALLBACK_EMAIL_CHECK', true);
if(function_exists('imap_rfc822_parse_adrlist'))
{
/**
* Get the host part (domain) of an email address.
*
* @param string|null $email email address, can be null
* @return string|null host part of the email address if the address is valid, otherwise NULL
*/
function get_host_from_email_addr(?string $email) : ?string
{
if(null === $email)
return null;
@[$obj, $obj2] = imap_rfc822_parse_adrlist($email, '');
imap_errors(); // flush errors, otherwise unsuppressable notifications on wrong format are shown due to external calls
// we want to allow 'simple email addresses' only and therefore exact the 2 properties:
// ->mailbox and ->host
return (isset($obj->mailbox, $obj->host) && !isset($obj2) && 2 === count(get_object_vars($obj)))
? $obj->host ?: null
: null
;
}
}
else if(defined('ALLOW_FALLBACK_EMAIL_CHECK') && ALLOW_FALLBACK_EMAIL_CHECK)
{
function get_host_from_email_addr(?string $email) : ?string
{
// This probably ensures getting a valid host name from email address.
// However, filter_var works too restrictive generating false negatives.
return filter_var($email, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE) ? array_slice(explode('@', $email), -1)[0] : null ;
}
}
else
throw new Error('Unresolved dependency: Please install php-imap module or set constant ALLOW_FALLBACK_EMAIL_CHECK to TRUE.');
$isp_names =
[
'gmail.com' => 'Gmail',
'outlook.com' => 'Outlook',
];
$isp = @$_GET['isp'] ?: $isp_names[get_host_from_email_addr(@$_GET['input_value'])] ?? 'unknown';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.