在上一節的 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>
以上代碼存在的問題是,未經授權的用戶可透過輸入表單在郵件頭部插入資料。
假如使用者在表單中的輸入框內加入以下文字到電子郵件中,會出現什麼情況呢?
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() 函數把上面的文字放入郵件頭部,那麼現在頭部有了額外的 Cc:、Bcc: 和 To: 欄位。當使用者點擊提交按鈕時,這封 e-mail 會被送到上面所有的地址!
PHP 防止 E-mail 注入
防止 e-mail 注入的最佳方法是對輸入進行驗證。
下面的程式碼與上一章的類似,不過這裡我們已經增加了偵測表單中email 欄位的輸入驗證程式:
<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 篩選器來驗證輸入:
FILTER_SANITIZE_EMAIL 過濾器從字串中刪除電子郵件的非法字元
FILTER_VALIDATE_EMAIL 過濾器驗證電子郵件地址的值
以上就是中文 Secure E-mails的內容,更多相關內容請注意PHP網(wwwure E-mails. php.cn)!