PHP 安全 E-mail

2021-11-19 16:46 更新

我們在上一節(jié)內(nèi)容中已經(jīng)介紹過 PHP 發(fā)送電子郵件的方式了,但是在上一節(jié)中的 PHP e-mail 腳本中,存在著一個漏洞,接下來我們一起來解決這個漏洞!


PHP E-mail 注入

首先,請看上一章中的 PHP 代碼:

<html>
 <body>

 <?php
 if (isset($_REQUEST['email']))
 //if "email" is filled out, send email
 {
 //send email
 $email = $_REQUEST['email'] ;
 $subject = $_REQUEST['subject'] ;
 $message = $_REQUEST['message'] ;
 mail("someone@example.com", "Subject: $subject",
 $message, "From: $email" );
 echo "Thank you for using our mail form";
 }
 else
 //if "email" is not filled out, display the form
 {
 echo "<form method='post' action='mailform.php'>
 Email: <input name='email' type='text'><br>
 Subject: <input name='subject' type='text'><br>
 Message:<br>
 <textarea name='message' rows='15' cols='40'>
 </textarea><br>
 <input type='submit'>
 </form>";
 }
 ?>

 </body>
 </html> 

以上代碼存在的問題是,未經(jīng)授權(quán)的用戶可通過輸入表單在郵件頭部插入數(shù)據(jù)。

假如用戶在表單中的輸入框內(nèi)加入如下文本到電子郵件中,會出現(xiàn)什么情況呢?

someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com

與往常一樣,mail() 函數(shù)把上面的文本放入郵件頭部,那么現(xiàn)在頭部有了額外的 Cc:、Bcc: 和 To: 字段。當(dāng)用戶點(diǎn)擊提交按鈕時,這封 e-mail 會被發(fā)送到上面所有的地址!


PHP 防止 E-mail 注入

防止 e-mail 注入的最好方法是對輸入進(jìn)行驗(yàn)證。

下面的代碼與上一章中的類似,不過這里我們已經(jīng)增加了檢測表單中 email 字段的輸入驗(yàn)證程序:

<html>
 <body>
 <?php
 function spamcheck($field)
 {
 //filter_var() sanitizes the e-mail
 //address using FILTER_SANITIZE_EMAIL
 $field=filter_var($field, FILTER_SANITIZE_EMAIL);

 //filter_var() validates the e-mail
 //address using FILTER_VALIDATE_EMAIL
 if(filter_var($field, FILTER_VALIDATE_EMAIL))
 {
 return TRUE;
 }
 else
 {
 return FALSE;
 }
 }

 if (isset($_REQUEST['email']))
 {//if "email" is filled out, proceed

 //check if the email address is invalid
 $mailcheck = spamcheck($_REQUEST['email']);
 if ($mailcheck==FALSE)
 {
 echo "Invalid input";
 }
 else
 {//send email
 $email = $_REQUEST['email'] ;
 $subject = $_REQUEST['subject'] ;
 $message = $_REQUEST['message'] ;
 mail("someone@example.com", "Subject: $subject",
 $message, "From: $email" );
 echo "Thank you for using our mail form";
 }
 }
 else
 {//if "email" is not filled out, display the form
 echo "<form method='post' action='mailform.php'>
 Email: <input name='email' type='text'><br>
 Subject: <input name='subject' type='text'><br>
 Message:<br>
 <textarea name='message' rows='15' cols='40'>
 </textarea><br>
 <input type='submit'>
 </form>";
 }
 ?>

 </body>
 </html> 

在上面的代碼中,我們使用了 PHP 過濾器來對輸入進(jìn)行驗(yàn)證:

  • FILTER_SANITIZE_EMAIL 過濾器從字符串中刪除電子郵件的非法字符
  • FILTER_VALIDATE_EMAIL 過濾器驗(yàn)證電子郵件地址的值

您可以在我們的 PHP Filter 中閱讀更多關(guān)于過濾器的知識。

結(jié)合本節(jié)與上一節(jié)的內(nèi)容,你就可以在 PHP 中安全的發(fā)送電子郵件了!


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號