Php – How to pass PHP mail.log output to a script

emailloggingPHP

I'm logging all php mail output using the mail.log setting in php.ini. Rather than log to a file I want to have the log data sent to a script for parsing in real-time to raise alerts.

I have tried:
mail.log="|/path/to/script.php"

in the hope that it might work like /etc/aliases, but that doesn't work. Any ideas greatly appreciated 🙂

System is Postfix on Debian.

Best Answer

One possible solution would be to use a wrapper for sendmail command, for example you can create a script like this:

#!/bin/sh
# file: sendmail-wrapper-php
# env vars: ${HTTP_HOST}, ${REMOTE_ADDR}, ${SCRIPT_NAME}, ${PWD}, ${UID}

# ....
# check and alert 

#send email.
/usr/sbin/sendmail -t -i $*

and php_set_envs.php to sets some PHP variables to the shell environment:

<?php
putenv("HTTP_HOST=".@$_SERVER["HTTP_HOST"]);
putenv("SCRIPT_NAME=".@$_SERVER["SCRIPT_NAME"]);
putenv("SCRIPT_FILENAME=".@$_SERVER["SCRIPT_FILENAME"]);
putenv("DOCUMENT_ROOT=".@$_SERVER["DOCUMENT_ROOT"]);
putenv("REMOTE_ADDR=".@$_SERVER["REMOTE_ADDR"]);

Now you force all customers to use this wrapper script instead of the original /usr/sbin/sendmail binary. Modify your php.ini and add/change:

sendmail_path = /usr/sbin/sendmail-wrapper-php
auto_prepend_file = /www/php/php_set_envs.php

Make sure it has correct access permissions:

$ chown root /usr/sbin/sendmail-wrapper-php
$ chmod 755 /usr/sbin/sendmail-wrapper-php

I hope this help.

Related Topic