php Secure email ,防止郵件注入

來源:互聯網
上載者:User

標籤:

PHP Secure E-mails

在上一節中的 PHP e-mail 指令碼中,存在著一個漏洞。

PHP E-mail 注入

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

<html><head><meta charset="utf-8"><title>測試教程(test.com)</title></head><body><?phpif (isset($_REQUEST[‘email‘])) { // 如果接收到郵箱參數則發送郵件// 發送郵件$email = $_REQUEST[‘email‘] ;$subject = $_REQUEST[‘subject‘] ;$message = $_REQUEST[‘message‘] ;mail("[email protected]", $subject,$message, "From:" . $email);echo "郵件發送成功";} else { // 如果沒有郵箱參數則顯示表單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>

以上代碼存在的問題是,未經授權的使用者可通過輸入表單在郵件標頭部插入資料。

假如使用者在表單中的輸入框內加入如下文本到電子郵件中,會出現什麼情況呢?

[email protected]%0ACc:[email protected]%0ABcc:[email protected],[email protected],[email protected],[email protected]%0ABTo:[email protected]

與往常一樣,mail() 函數把上面的文本放入郵件標頭部,那麼現在頭部有了額外的 Cc:、Bcc: 和 To: 欄位。當使用者點擊提交按鈕時,這封 e-mail 會被發送到上面所有的地址!

PHP 防止 E-mail 注入

防止 e-mail 注入的最好方法是對輸入進行驗證。

下面的代碼與上一章中的類似,不過這裡我們已經增加了檢測表單中 email 欄位的輸入驗證程式:

<html><head><meta charset="utf-8"><title>測試教程(test.com)</title></head><body><?phpfunction spamcheck($field){// filter_var() 過濾 e-mail// 使用 FILTER_SANITIZE_EMAIL$field=filter_var($field, FILTER_SANITIZE_EMAIL);//filter_var() 過濾 e-mail// 使用 FILTER_VALIDATE_EMAILif(filter_var($field, FILTER_VALIDATE_EMAIL)){return TRUE;}else{return FALSE;}}if (isset($_REQUEST[‘email‘])){// 如果接收到郵箱參數則發送郵件// 判斷郵箱是否合法$mailcheck = spamcheck($_REQUEST[‘email‘]);if ($mailcheck==FALSE){echo "非法輸入";}else{// 發送郵件$email = $_REQUEST[‘email‘] ;$subject = $_REQUEST[‘subject‘] ;$message = $_REQUEST[‘message‘] ;mail("[email protected]", "Subject: $subject",$message, "From: $email" );echo "Thank you for using our mail form";}}else{ // 如果沒有郵箱參數則顯示表單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 過濾器來對輸入進行驗證:

  • FILTER_SANITIZE_EMAIL 過濾器從字串中刪除電子郵件的非法字元
  • FILTER_VALIDATE_EMAIL 過濾器驗證電子郵件地址的值

php Secure email ,防止郵件注入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.