PHP CLI: Possible to set a $_SERVER Variable that's an Array?

1.5k Views Asked by At

When running PHP from the command line in bash, is it possible to set a $_SERVER variable that it, itself, an array?

That is, if I do something like this

$ export test=foo

and then run a program like this

<?php
#File: test.php
var_dump($_SERVER['test']);

the program will output the string value "foo". Is it possible to have $_SERVER['test'] be equal to a PHP array without extra PHP code?

The specific problem I'm trying to solve is I have a Symfony CLI based program I can't modify, and this program uses the $_SERVER variables to bootstrap its enviornment.

use Magento\Framework\App\Bootstrap;
use Magento\Framework\Shell\ComplexParameter;
//...
$bootstrapParam = new ComplexParameter(self::INPUT_KEY_BOOTSTRAP);
$params = $bootstrapParam->mergeFromArgv($_SERVER, $_SERVER);
$params[Bootstrap::PARAM_REQUIRE_MAINTENANCE] = null;
$bootstrap = Bootstrap::create(BP, $params);

The Bootstrap::create(BP, $params); recognizes some nested keys in $params -- I'm trying to find a way to change those values without modifying the CLI program itself.

2

There are 2 best solutions below

2
On

mergeFromArgv does not use whole $_SERVER array, but only $_SERVER['argv'] part of it, which is basically command line arguments as scalars.

The arguments seems to be parsed with parse_str then, so you should be able to pass a php array a as following:

php yourscript.php a[]=1\&a[]=2\&a[b]=anything

You may need to quote the string or escape characters depending on your shell.

2
On

you can set any server variable via .htaccess file or apache .conf file, you can do it using mod_env

SetEnv MY_EXAMPLE myexample_data

Then you can access that variable in php file

echo $_SERVER["MY_EXAMPLE"]; //outputs myexample_data

or while using PHP CLI you can set $_SERVER variable using followings

putenv('MY_EXAMPLE=myexample_data');