I am "forking" php code, kicking off scripts to run in the background allowing the browser application to continue without having to wait for a response.
I would like to be able to pass a parameter to such a script.
Say i have an array i would like to be accessible to the script in question, how could i pass it over?
$test = array(1,2,3);
//for windows i do the following which works well enough
pclose(popen("start php /path/to/script.php ","r"));
OR for some linux distro's :
exec('php -f /path/to/script.php >/dev/null 2>&1 &');
so firstly, is it possible to pass my array to that script? if its possible to make it accessible to the script, how could i access the passed variable in that script?
(sitting here confused, thinking about passing variable by value/reference....)
thanks!
Nicolas Brown is almost right. But that would be the second part of the solution you're looking for, I think.
As you maybe already know you can call a program from the console and yet pass any arguments the program might expect:
>php -f /path/to/program arg1[ arg2 ... argN] >/dev/null 2>&1 &
So as you're passing a string to exec()
why not just "insert" your array as arguments and then execute it
$test = array(1,2,3);
$args = implode($test, " ");
$prog = 'php -f /path/to/script.php ' . $args . ' >/dev/null 2>&1 &'
exec($prog);
Here comes something from the tutorial Nicolas Brown mentioned. In your script.php
you can get the parameters from $argv[]
$myParam1 = $argv[1];
$myParam2 = $argv[2];
Please, note that in argv[0] is the name of the program. That's exactly why in the tutorial they first do arry_shift($argv)
, to get rid off the first element (the program's name and path).
Hope it helps!
use the $argv variable
you can find an example from this tutorial
+1 to @Havelock for a thorough answer - just wanted to post a few additional implementation suggestions.
I actually had to implement exactly this recently :) The implementation path I went with was to serialize()
the array and pass that in as a command-line argument to the PHP script. This allows you to pass in arbitrary parameters to your script without having to do as much maintenance work with the arguments parsing.
I think serializing as json might even be a little friendlier than PHP serialization though. If you go that route though, and if windows / linux compatibility is important for your application (whether local development environment or otherwise) be sure to test out your serialized payload in both environments.
Windows doesn't seem to like quotes within the payload.
Oh and for debuggability, make sure to do some good logging within your PHP script - this kind of solution lends itself to fun debugging sessions.