I am trying to have a script start another script and put its data into a session variable for the other script to use. The problem is that when the second script, data.php, runs it doesn’t seem to be able to access the session variables. They are blank and nothing gets written to data.txt. If I run data.php by itself it writes the last value that $_SESSION["data"] was set to properly, but not when it’s run with exec. I am not sure what the problem is. Any ideas?
input.php:
session_start();
$_SESSION["data"] = "Data!";
exec("/usr/bin/php /path/to/data.php > /dev/null 2>&1 &");
data.php:
session_start();
$fp = fopen('data.txt', 'w');
fwrite($fp, $_SESSION["data"]);
fclose($fp);
Edit: I am trying to start data.php from inside input.php and have the variables from input.php accessible in data.php.
You can pass data to PHP scripts running with the CLI as command line arguments. This data will be available to the child script in the
$argvarray.input.php:
data.php
A couple of notes:
escapeshellarg()to ensure that users are not able inject commands into your shell. This will also stop special shell characters in arguments from breaking your scripts.$argvis a global variable, not a superglobal like$_GETand$_POST. It is only available in the global scope. If you need to access it in a function scope, you can use$GLOBALS['argv']. This is about the only situation in which I consider the use of$GLOBALSacceptable, although it is still better to handle the arguments in the global scope on startup, and pass them through the scopes as arguments.$argvis a 0-indexed array, but the first “argument” is in$argv[1].$argv[0]always contains the path to the currently executing script, because$argvactually represents the arguments passed to the PHP binary, of which the path to your script is the first.serialize()orjson_encode(). There is no way to pass resources through the command line.EDIT When passing vector types I prefer to use
serialize()because it carries with it information about the classes that objects belong to.Here is an example:
input.php:
data.php
Here is a couple of functions from my clip collection I use to simplify this process:
If you need to pass a large amount of data (larger than the output of
getconf ARG_MAXbytes) you should dump the serialized data to a file and pass the path to the file as a command line argument.