Piping email to a script with cPanel – redux

After some further experimentation, I believe I’ve got a more robust method for suppressing output from a PHP script that’s the end-point of a piped email address.

Previously, I structured my PHP file with a shebang line similar to the following:

#!/usr/bin/php -q
<?php
// Code goes here
?>

However, any die, echo or syntax-errors yielded by execution would cause output to be generated which the mailer would interpret as a failure. Given that you can cause output in a bunch of different ways (and that it can be hard to track down), let’s be a bit cleverer.

First off, make your processing script as before – read from STDIN, parse the email message and then do something with it. You’ll still need the shebang line though can leave out the -q this time.

Next, create a new script, this time with a shebang pointing us to Bash. For example:

#!/bin/bash
...

This script will simply run the PHP script, but redirect STDERR to STDOUT, and then STDOUT to /dev/null thus yielding no output at all regardless of what the script gets up to. By way of example:

#!/bin/bash
/home/<username>/processingscript.php > /dev/null 2>&1

The magic’s in the redirect to /dev/null, and then the redirect of STDERR (2) to STDOUT (1) at the end. Our PHP script will still have access to STDIN (where the raw email content’s waiting) because it inherits the descriptor from the script calling it (in this case, our Bash script).

We can test this by writing a very simple test script that’ll just dump the most recently received email to disk and then die so that we can both prove that it ran and that it didn’t cause an email bounce:

#!/usr/bin/php
<?php
   // Paste the mailRead method from the previous blog post in here

   file_put_contents('/home/<username>/output.txt', mailRead(-1));
   die('Ordinarily this die would cause a bounce...');
?>

Fire an email to your forwarded address and give it a minute. You should find a file output.txt with the raw contents of the email just received, and no bounce returned to the sender.

Make sure that both your Bash file and the PHP processing script are both marked as executable.

Leave a Reply

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

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