Forum Moderators: coopster

Message Too Old, No Replies

Passing variables to PHP running at the command line

         

usrbin

3:26 pm on Aug 21, 2016 (gmt 0)

5+ Year Member Top Contributors Of The Month



My host allows me to create "email recipes". One recipe is an "email filter" which allows me to "pass e-mail messages through a program or script.". When setting up the filter I enter a command that will be interpreted using the sh shell when an email comes in to the email address being setup.

I setup my command as "/usr/local/bin/php /path/to/script.php" and I've verified that this runs. My problem is figuring out how to grab the email properties such as the "from", "subject", and "body" fields. I've tried to see what variables are present when the script runs which are _GET, _POST, _COOKIE, _FILES, argv, argc, and _SERVER, but looking at these arrays I don't see these fields being passed.

I'm guessing I need to alter how the command is setup in order to send this data into the script. Does anyone have any direction on how I can achieve that?

Andy Langton

6:26 pm on Aug 21, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There's no $_GET or $_POST arrays on the command line, but you can pass arguments like this:

php /path/to/script.php arg1 arg2 arg3


You can access the values via $argv[1] etc.

You would likely need to parse these values slightly differently than if accessing by the web - one mechanism is to 'rebuild' this into a format similar to a $_POST or $_GET array to allow for processing both on the command line and web. You can also check PHP_SAPI for how the script is being executed.

You can also avoid this by using wget or something similar to actually request the script over the web, depending on what sort of data you're passing to the script.

usrbin

12:00 am on Aug 22, 2016 (gmt 0)

5+ Year Member Top Contributors Of The Month



Awesome! That works great. Now on the command line side, are there any common variables for things like from and subject line?

php /path/to/script.php from subject

Andy Langton

9:00 am on Aug 22, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



if you pass an argument like from=me@example.com&subject=email you can use parse_str [php.net] to turn it into an array.

I.e.


> php /path/to/script.php from=me@example.com&subject=email
parse_str($argv[1],$values);
echo $values['from']; // me@example.com
echo $values['subject']; // email


Obviously, use caution if any of that data is user-supplied (e.g. I can submit a subject of hackedvariable=unsanitised).

usrbin

8:59 pm on Aug 24, 2016 (gmt 0)

5+ Year Member Top Contributors Of The Month



Thanks, but I was trying to find what the email address and subjects of the incoming emails were which are unknown and always changing. I ended up figuring out how to do that by reading the stdin inside the php script.