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 过滤器验证电子邮件地址的值
以上就是php secure e-mails的内容。
