I need to run a PHP script from command line and I need to set some environmental variables. Unfortunately, following does not work:
php -dAPPLICATION_ENV=staging script.php
What I'd like to accomplish is having APPLICATION_ENV variable set.
APPLICATION_ENV=staging php script.php
The variable will be available in the $_SERVER array:
echo $_SERVER['APPLICATION_ENV'];
There is no way to set environment variables from the command line specifically for the execution of a script by passing options to the PHP binary.
You have a few options:
Set the variable globally on the system.
Set the variable on the command line before calling the script. This will persist in the environment after your script has finished executing, which you may not want.
Wrap the PHP script in another script, allowing you to create a temporary variable that exists only for the duration of the script.
Use a command line option instead of an environment variable.
The last two options are probably the cleanest way to do this, in that the variable created only exists for the run time of your script.
The implementation of option 1 is system dependent.
The implementation of option 2 is also system dependent - on Windows you would do set APPLICATION_ENV=staging&& php script.php and on *nix it would be export APPLICATION_ENV='staging' && php script.php.
If you were to go for option 3 you might be tempted to go for a shell script, but this is not portable (you would need a batch file for Windows and a shell script for *nix environments. Instead, I'd suggest you write a simple PHP wrapper script, something like this:
<?php
putenv('APPLICATION_ENV=staging');
include('script.php');
This allows you to leave your target script unchanged and set the environment variable for the script's session only.
A more complex wrapper script could easily be created which would allow you to specify variables on the command line, and even dynamically specify the script which should be executed when these variables are set.
Option 4 can be implemented using the $argv variable:
<?php
$applicationEnv = $argv[1];
// rest of you script
...and call the script like:
php script.php staging
However, it occurs to me that you seem to be indicating to the script which environment is running in (staging, dev, live, etc) - in which case it might be simplest to set a server-wide variable, and rename it as necessary to prevent collision with variables that other applications may be setting. That way you can simply invoke the script and not need to worry about this. This is assuming that you staging environment runs on a different machine to the live (which it should be).
When you execute a PHP script from the command line, it inherits the environment variables defined in your shell. That means you can set an environment variable using the export command like so:
export APPLICATION_ENV='staging'
Here is an example for setting one envirnnomental variable :
ENV_VAR='var' php script.php
Just in case you want to set multiple variables
Try this :
ENV_VAR1=1 ENV_VAR2=2 ENV_VAR3=3 php script.php
You can set a variable in /etc/environment like FOO="bar" which is then accessible with getenv() in both CLI and web requests. You may need to relog for this change to take effect.
Try using putenv and pass the variables through parameters
php script.php APPLICATION_ENV=staging
And in the script.php code:
for($i=1;$i<count($argv);$i++){
putenv($argv[$i]);
}
I have the same situation and i use next code (it works for me):
export APPLICATION_ENV=staging && php script.php
Hope it will helpful for you too.
Related
I'm looking for a way to export an environment variable from a PHP script running with PHP CLI. The putenv function only permit to set variable that will be existing during script execution, not after.
My use case is a PHP script used as bash autocompleter function. In this type of function, we have to set COMPREPLY variable that must contain the list of available options (as a bash array). Currently, I'm setting this variable by this way :
COMPREPLY=( $(php myscript.php) )
I would like to have possibility to set COMPREPLY variable and some others (especially for action on default behavior on empty options list).
Thank you in advance
I want to be able to access environment variables set in Powershell from within my PHP script.
Normally in Linux systems export SOMETHING=foo would work and in Windows CMD SET SOMETHING=bar would also work. But I don't know how to make this work with Powershell CLI (not script) as well.
I have tried using Set-Variable -Name "SOMETHING" -Value "foo", but that didn't get read by PHP.
Within my PHP script I simply want to use getenv('SOMETHING');.
There are several ways to create environment variables in PowerShell. It is important to distinguish between PowerShell variables (e.g. $myVar) and Environment variables as you might know them from the good old command prompt (e.g. in cmd SET MYVAR=MYVAL).
To create an environment variable in PowerShell, the easiest way is to create a new Item in the environment (Env):
New-Item Env:/VarName -Value "Foo"
The code example you posted
Set-Variable -Name "Name" -Value "value"
creates a PowerShell variable, but it's easier to just write $Name = "value".
PowerShell variables are only visible in your PowerShell scope. Environment variables can be read by any program you start as a sub process in the current environment (e.g. PowerShell session).
EDIT:
The example posted in the comments by #f64a is interesting too:
[environment]::SetEnvironmentVariable("myName", "myValue",[System.EnvironmentVariableTarget]::Machine)
It is afaik the only way to manipulate environment variables via PowerShell out of your own scope. With EnvironmentVariableTarget you can choose where your variable is manipulated. Be aware that you might need higher privileges to manipulate these.
Here is how I set the variable within my Apaches VirtualHost Container
SetEnv MY_VAR "/opt/"
Now, PHP can perfectly access this vairable:
echo $_SERVER['MY_VAR'];
/opt/
However, if I call a shell script from my PHP code
passthru('/path/to/myscript');
MY_VAR is empty within /path/to/myscript.
If I however modify the call like this, it works:
passthru('export MY_VAR='. $_SERVER['MY_VAR'] .'; /path/to/myscript');
Is there a better way to pass all environment variables to the shell script? Since I need to pass multiple ones.
I also tried system(), exec(), backticks and shell_exec(). They all show the same behavior, as passthru().
If you use putenv("MY_VAR=test"); the environment value is passed on to the invoked shell command. (but it is not put in $_ENV)
So you could simply do something like
foreach ( $_SERVER as $k=>$v ) putenv("$k=$v");
Try proc_open.
proc_open('/path/to/myscript', $descriptorspec, $pipes, null, $_SERVER);
You could pass an array with the environment variables as an option.
If you use phpinfo() in your first page, you will see that your env variable (MY_VAR) is not listed in the "Environment" box, but in the "Apache Environment" (if this is the webserver you use).
So, it seems that "getenv" not only gets its values from the environment, but also from Apache environment, which (it seems) is not inherited when launching something by passthru.
In the script executed by passthru, I only see env. vars listed in the "Environment" box, so it is consistent.
So, for each variable you want to export to the passthru script, you should use:
putenv('MY_VAR ='.apache_getenv('MY_VAR'));
Easy to do with an array and a for loop.
I guess it's because when you call SetEnv you're modifing your current shell environment. When you subsequently when you call passthru, your existing env is destroyed along with any non exported variables, and a "fresh" environment given to /path/to/myscript.
Can you instead pass env variables on the command line, as parameters to the /path/to/myscript -MY_VAR=/opt ?
If I set a variable using putenv, will other scripts be affected by this.
My understanding is that it is script specific, is that correct? if two different scripts are running at the same time on the server, will it affect the other script?
Yes, the env vars are specific to each particular invocation of a program/script. Just like each program can have its own working directory, its own stdin/stdout/stderr, etc... One script's environment cannot affect another's, unless they're in a parent/child relationship.
No, other scripts will not be affected.
The environment variable will only exist for the duration of the current request.
The following sample code can be run using the PHP CLI utility.
<?php
putenv("FOO=bar");
print("PHP says FOO=" . getenv("FOO") . "\n");
?>
Here is the output of the program and the resulting environment.
$ php putenv.php; echo echo says FOO=$FOO
PHP says FOO=bar
echo says FOO=
I am a newbie with shell scripting so need a few ideas on parsing a PHP file using a shell script.
Ours is a PHP project and I am improving our shell script which is used to upload code to production server.
There is one PHP config file production.settings.php which needs to be read during upload, for a few constants -
BASE_PATH (path to project root on prod server)
db_host, db_name etc. (database settings of prod database - to be used for taking a backup of the database before upload)
Question
How to read the value of the constants?
They are defined like this:
define("BASE_PATH","/path/to/project/root");
How to read the first uncommented value of the constant?
Note - The constant may be defined more than once in the same file (let's assume the possibilty - this may happen by mistake or there may be commented instances of the line)
So far I am only able to get the number of lines containing the string define("BASE_PATH" using grep in my shell script -
cd ..
PROJECT_ROOT=$PWD
result= grep -ic 'define("BASE_PATH",' $PROJECT_ROOT'/config/main.settings.php'
echo "see"$result
Is this method of parsing good enough or a yml file would be better? Is there any shell command/snippet for doing this so that I can get the result by writing lesser amount of code?
Updates
Check my other questions for more details on this:-
Manipulating an array (printed by php-cli) in shell script,
Assigning values printed by PHP CLI to shell variables,
Initiating dynamic variables (variable variables) in bash shell script
just do it using the php, then call your shell script to invoke the php script.
Assuming you have your bunch of defines defined in defs.php:
define('NAME', 'JOHN');
define('HOBBY', 'FISHING');
then create a php script get_defs.php:
require_once 'defs.php';
$const = get_defined_constants(true);
foreach($const['user'] as $k => $v) {
echo "export $k=$v";
}
then in your shell script, run it like so:
`php get_defs.php`
What happen is, get_defs.php will output bunch of export KEY=VALUE, then shell will run those commands outputted by your php get_defs.php.
Why don't you just code with PHP CLI? That's what you understand? Also maybe you could put constants in a ini file and read them?
If youre comforttable with PHP then use PHP to write the shell script. IF you go this route i would move all config settings to a config file... INI, YAML, XML, whetever floats your boat. Then i would modify the bootstrap of the application that defines your constants to also read from this config file. That way you can use it in botht your script and the app without having to change it.