如何记录邮件发送与PHP的邮件()功能检测表单垃圾邮件
版本1.0
作者:Till Brehm
如果您正在运行Web服务器,您可能已经遇到了这个问题:您的服务器上的某个位置是一个易受攻击的联系人表单或用PHP编写的CMS系统,被垃圾邮件发送者滥用通过您的服务器发送电子邮件。 如果您有多个网站,那么检测哪些网站是易受攻击的,并发送垃圾邮件是一件很痛苦的事情。 本教程介绍了安装一个小型封装脚本,其中记录了通过PHP mail()函数发送的电子邮件。
我在本教程中使用Debian Linux,但脚本应该可以在任何Linux发行版上工作。
1安装包装器脚本
打开一个新文件/ usr / local / bin / phpsendmail ...
vi /usr/local/bin/phpsendmail
...并插入以下脚本代码:#!/usr/bin/php
/**
This script is a sendmail wrapper for php to log calls of the php mail() function.
Author: Till Brehm, www.ispconfig.org
(Hopefully) secured by David Goodwin
*/
$sendmail_bin = '/usr/sbin/sendmail';
$logfile = '/tmp/mail_php.log';
//* Get the email content
$logline = '';
$pointer = fopen('php://stdin', 'r');
while ($line = fgets($pointer)) {
if(preg_match('/^to:/i', $line) || preg_match('/^from:/i', $line)) {
$logline .= trim($line).' ';
}
$mail .= $line;
}
//* compose the sendmail command
$command = 'echo ' . escapeshellarg($mail) . ' | '.$sendmail_bin.' -t -i';
for ($i = 1; $i < $_SERVER['argc']; $i++) {
$command .= escapeshellarg($_SERVER['argv'][$i]).' ';
}
//* Write the log
file_put_contents($logfile, date('Y-m-d H:i:s') . ' ' . $_ENV['PWD'] . ' ' . $logline, FILE_APPEND);
//* Execute the command
return shell_exec($command);
?>
如果您使用与Debian不同的Linux发行版,则sendmail二进制文件可能与/ usr / sbin / sendmail位于不同的位置,您必须更改$ sendmail_bin ='/ usr / sbin / sendmail'行中的sendmail路径; 的脚本。
现在使脚本可执行...
chmod +x /usr/local/bin/phpsendmail
...并创建日志文件并使其可写:
touch /var/log/mail.form
chmod 777 /var/log/mail.form
2修改php.ini
现在我们重新配置PHP,以便它使用我们的包装器脚本发送电子邮件。
打开php.ini文件...
vi /etc/php5/apache2/php.ini
...并改变行...[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25
; For Win32 only.
;sendmail_from = me@example.com
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
... 至:[mail function]
; For Win32 only.
;SMTP = localhost
;smtp_port = 25
; For Win32 only.
;sendmail_from = me@example.com
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = /usr/local/bin/phpsendmail
如果您使用php作为cgi,使用suphp或fcgi,那么在/etc/php5/cgi/php.ini文件中更改相同的行。
重新启动Apache Web服务器以应用更改。
/etc/init.d/apache2 restart
3测试设置
要测试此设置,请在您的一个网站中创建一个名为mailtest.php的新的php文件,其中包含以下内容:<?php
mail('yourname@yourdomain.com','This is a test message subject','This is a test message body');
echo 'Mail sent.';
?>
然后在web浏览器中打开文件来执行它。 测试消息应该立即记录到日志文件中。 使用命令检查:
cat /var/log/mail.form