Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

piping, how to do it

Status
Not open for further replies.

elck

Programmer
Apr 19, 2004
176
NL
Hi,

Suppose I could forward my mail like this:

Code:
|/bin/sh -c '/usr/bin/php /path/to/your/script.php >> /path/to/an/outputfile.txt'

How do I get access to the mailcontent inside the script.php?

In other words, what does php do with the file that is piped to it?

I cannot find it in the manual, because i have no clue where to look!

Thanks
Elck
 
If you google for "pipe email php" you will find many hits which discuss this very topic. But, everyone seems to use some variant of the following code. Please note that this code works only with text email and will break HTML or other MIME based email messages.
Code:
#!/usr/bin/php
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
    $email .= fread($fd, 1024);
}
fclose($fd);
// handle email
$lines = explode("\n", $email);

// empty vars
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;

for ($i=0; $i<count($lines); $i++) {
    if ($splittingheaders) {
        // this is a header
        $headers .= $lines[$i]."\n";

        // look out for special headers
        if (preg_match("/^Date: (.*)/", $lines[$i], $matches)) {
            $date = $matches[1];
        }
        if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
            $subject = $matches[1];
        }
        if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
            $from = $matches[1];
        }
    } else {
        // not a header, but message
        $message .= $lines[$i]."\n";
    }

    if (trim($lines[$i])=="") {
        // empty line, header section has ended
        $splittingheaders = false;
    }
}
?>
You will notice that this script doesn't do anything with the parsed messages. That is an exercise for the people who use the script. :)

Ken
 
That's much more than I asked for Ken! ;)

The
Code:
$fd = fopen("php://stdin", "r");
part was what I was looking for!

But thanks for the extra anyway!


Regards,

Elck
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top