When a web server hosting multiple PHP applications or CMS sites is compromised by spammers, identifying the exact malicious PHP script sending unauthorized emails can be notoriously difficult. In PHP 5.3 and newer, built-in configuration directives allow you to track the exact script filename and originating source of every outgoing message.
mail.log for auditing script paths • mail.add_x_header for tracking script UID in email headers.
1. Enable mail.log
Open your server's php.ini (or pool configuration in PHP-FPM) and configure a dedicated mail log:
; Log all mail() function invocations, including script path and line number
mail.log = /var/log/php_mail.log
Ensure the web server user (e.g. apache or www-data) has write permissions to the destination file:
touch /var/log/php_mail.log
chown www-data:www-data /var/log/php_mail.log
chmod 660 /var/log/php_mail.log
2. Enable X-PHP-Originating-Script Header
To embed the sender script path directly into outgoing mail headers, enable mail.add_x_header:
; Adds X-PHP-Originating-Script header containing the UID and filename
mail.add_x_header = On
When an email is sent, the recipient headers will contain:
X-PHP-Originating-Script: 1000:contact_form.php
This allows you to immediately trace spam reports back to the offending script or compromised user account.