Identifying Email Spam From PHP

By | January 26, 2014

One of the biggest concerns when you manage a web server is security. Sure, you need to make sure no one hacks your machine to gain access to SSH, FTP, but how do you know if you have a security problem with one of your PHP scripts and it starts sending tons of email spam messages?

One of the most useful feature added in PHP 5.3 is the option to add some custom X headers when emails are sent in order to track the messages and to log all emails sent from PHP. Now how awesome is that?

You can configure it pretty easily by adding these 2 lines in /etc/php.ini in [mail function] section:

mail.add_x_header = On
mail.log = /var/log/php_mail.log

The first option will add an  X-PHP-Originating-Script header to the emails send from your servers, which looks like this:

X-PHP-Originating-Script: 500:contact.php

The mail.log option will create a new log file with an entry for each email sent.

Please note that you should create the log file with proper permissions first. If your web server runs with nginx user you can do the following:

touch /var/log/php_mail.log
chown nginx.nginx /var/log/php_mail.log

Note: If you use PHP-FPM, you will need to do a reload first:  /etc/init.d/php-fpm reload

You should also add an entry to rotate the log:

vim /etc/logrotate.d/php_mail

Add the following (press INSERT first):

/var/log/php_mail.log {
    rotate 5
    create 664 nginx nginx

Save the file (press Esc and then :wq Enter).

To test it, send an email from one of your PHP scripts. You should see an entry like this in /var/log/php_mail.log:

[26-Jan-2014 07:54:58 UTC] mail() on [/home/bubble/public_html/]: To: [email protected] -- Headers: Date: Sun, 26 Jan 2014 07:54:58 +0000 Return-Path: [email protected] From: test  Message-ID: <[email protected]> X-Priority: 3 X-Mailer: PHPMailer 5.2.4 MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Content-Type: text/plain; charset=UTF-8

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.