The register_argc_argv option must be enabled in the PHP configuration file (php.ini). This setting loads command-line arguments and query params into $_SERVER['argv']. https://www.php.net/manual/en/ini.core.php#ini.register-argc-argv
This Symfony code uses input arguments (ArgvInput) to determine the values of certain environment variables, specifically APP_ENV and APP_DEBUG. Here are the relevant parts of Symfony’s code:
//Symfony\Component\Runtime\SymfonyRuntime
$input = new ArgvInput();
if (isset($this->options['env'])) {
return $this->input = $input;
}
if (null !== $env = $input->getParameterOption(['--env', '-e'], null, true)) {
putenv($this->options['env_var_name'].'='.$_SERVER[$this->options['env_var_name']] = $_ENV[$this->options['env_var_name']] = $env);
}
if ($input->hasParameterOption('--no-debug', true)) {
putenv($this->options['debug_var_name'].'='.$_SERVER[$this->options['debug_var_name']] = $_ENV[$this->options['debug_var_name']] = '0');
}
The code above processes arguments provided through ArgvInput. If the --env parameter is specified in argv, it updates the environment variable APP_ENV accordingly. Similarly, if --no-debug is present, it sets APP_DEBUG to 0.
The ArgvInput class initializes argv parameters passed via the command line, query params or by default, those in $_SERVER['argv']. The array_shift($argv); function removes the first element from the $argv array (normally the application name) and stores the remaining arguments in $this->tokens.
//Symfony\Component\Console\Input\ArgvInput
public function __construct(?array $argv = null, ?InputDefinition $definition = null)
{
$argv ??= $_SERVER['argv'] ?? [];
// strip the application name
array_shift($argv);
$this->tokens = $argv;
parent::__construct($definition);
}
Using the following URL: http://localhost/?+--env=dev, we can inject a --env=dev argument into $_SERVER['argv']. This allows us to change the APP_ENV value to dev without modifying the application’s configuration directly.
- When accessing http://localhost/?+--env=dev, $_SERVER['argv'] might look like this:
$_SERVER['argv'] = ["+--env=dev"];
- In the ArgvInput class, after the array_shift operation, $argv becomes:
$argv = ["--env=dev"];
- ArgvInput will then recognize --env=dev as a valid parameter and will update APP_ENV accordingly through the getParameterOption method.