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 { missingok daily rotate 5 notifempty 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: