I need to access an environment variable in my php script. It's running on a remote server. I've added them to /etc/environment but I can't access them as the server needs a reboot.
They can be echoed when I run
source /etc/environment
so it's not a problem with the file.
But the php script isn't running as my user so it doesn't have those variables. Since it's a remote server I don't particularly want to reboot it, as I assume this would then pull in the new environment variables I wrote to /etc/environment.
I've seen I can use /etc/profile but that won't affect the apache user, which I assume is running the php scripts.
I've tried to run
echo exec('source /env/environment && echo $the_var');
but the variable still doesn't return.
Any ideas please?
Thanks in advance
Related
I am trying to work with an OpenAI library (https://github.com/orhanerday/open-ai) that uses environment variables for key storage, but it doesn't seem to be finding the key when I run it.
On my local Windows machine I ran the following command: setx OPENAI_API_KEY “mykey”
On the Linux web server I ran the following command: export OPENAI_API_KEY=mykey
Now on the server when I run the following, I see the correct key value printed back to me: printenv OPENAI_API_KEY
In my script I'm using $open_ai_key = getenv('OPENAI_API_KEY'); but I'm getting no value back..??
Any information on how I can resolve this would be greatly appreciated. Thanks!
Thank you for using orhanerday/OpenAI PHP SDK,
Let's try to set your ‘OPENAI_API_KEY’ Environment Variable through the Control Panel
Open System properties and select Advanced system settings
Select Environment Variables...
Select New… from the User variables section(top). Add your name/key-value pair, replacing with your API key.
Variable name: OPENAI_API_KEY
Variable value: <yourkey>
Sign out and then log in to your PC.
Create a PHP file;
<?php
$open_ai_key = getenv("OPENAI_API_KEY");
print("OPENAI_API_KEY is; $open_ai_key");
run the PHP file
$ php index.php
> OPENAI_API_KEY is: sk-gjtv.....
After running the app you should get the value.
I'm running Apache on a Linux server. There are a collection of shell scripts that need to get executed by a PHP script. Apache/PHP on the server is only needed for this one purpose. The shell scripts must be executed by user "X". I've set the User and Group properties in httpd.conf to be for user "X" and its group.
When I call the PHP script, I've included an echo of whoami. It shows user "X". I've also included an output to log file in the shell script that PHP executes that echos whoami and env variables. When the shell script runs, it reports that the user is "X", but the env variables output shows the user to be ROOT. How is this possible? This is ultimately a problem as the shell script won't run properly if it doesn't have access to the env variables for user "X".
[edit]
Further clarification. The issue exists at the PHP script level too, so to simplify things, I can rephrase the issue that when I have Apache configured in httpd.conf to run as user "X", and if I trigger a PHP script that echos "whoami" and "env", then I see that "whoami" is user "X" but the "env" details are for user "root". the PHP script would look something like this...
<?php
echo "<br>". exec('whoami');
exec('env', $envo);
echo "<br>". print_r($envo);
?>
whoami prints the effective user id.
When you start Apache, I guess you do it using the root user, or with some sudo rule. This is required to let Apache bind ports below 1024 (so the default 80 HTTP or 443 HTTPS qualify).
In your Apache config, you put User X (and probably Group X). This tells Apache that once the first process is started (via root), all other children processes will run under the X:X user and group.
So in your PHP code, when you run whoami it returns the effective ID of the process PHP runs in. This is X, since the process is a child of the first process.
But when you run env it runs the environment under which the child process was started. This environment was inherited from the first process, which is started by root. Hence you see the env of root.
Your fix is ok.
I never did figure out the discrepancy between output from "whoami" and "env". However, I found that I could successfully get the environment variables set properly by creating a shell script with exports for the needed variables and then calling that via "source" before calling my target shell script. For example, in PHP...
exec('source /home/X/setEnvironment.sh && /home/X/scripts/targetScript.sh');
This worked.
I have some PHP scripts for database maintenance in my server that requires its periodically execution. Obviously the easiest solution is to schedule its running with system cron.
The scripts require some server variables accessed from $_SERVER, like database hostname, cron parameters, etc.
I can run the scheduled cron commands from command line without any problem, and everything seems to be working fine (calling something like php filename.php). However, when the same commands are executed from cron, the scripts fails and the error reported is like the following:
PHP Notice: Undefined index: RDS_DATABASE in
/var/app/current/app/xx/Db/ConnectionFactory.php on line 8 PHP
Seems that the $_SERVER variable is not correctly initialized when running from cron, but it works from command line. I have tried with crontab -u ec2-user -e but without luck.
I do not want to use wget to run the script as it adds some overhead, and the scripts are hidden from being accessed from HTTP.
Any hint about successfully accessing $_SERVER from command line, but failing when running from crontab?
Had the same issue. Found a solution:
echo "InstanceID: ".get_cfg_var('INSTANCE_ID')."\n";
For some reason it was working fine on my ec2 user but not as a root cron job. Using the function instead of accessing the $_SERVER array solved my problem.
$_SERVER only works if you will run PHP using any web server. If you will use crontab and execute PHP via command line it will not work. You may refer to PHP documentation http://php.net/manual/en/reserved.variables.server.php#refsect1-reserved.variables.server-indices
As #Baminc and #Ankur says the solution is to use get_cfg_var function to get the information because $_SERVER only works when you access it from a web browser.
What I do is the following for example with SERVER_NAME :
if (isset($_SERVER['SERVER_NAME'])) {
$myServerName = $_SERVER['SERVER_NAME'];
} else {
$myServerName = get_cfg_var('SERVER_NAME');
}
Hope this helps!
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.
First, I read some threads by people with similar problems but all answers didn't go beyond export DISPLAY=:0.0 and xauth cookies. So here is my problem and thanks in advance for your time!
I have developed a little library which renders shelves using OpenGL and GLSL.
Last few days I wrapped it in a php extension and surprisingly easy it works now.
But the problem is it works only when I execute the php script using the extension from commandline
$php r100.php(i successfuly run this from the http user). The script is in the webroot of apache and if I request it from the browser I get ** CRITICAL **: Unable to open display in apache's error_log.
So, to make things easier to test and to be sure that the problem is not in the library/extension, at the moment I just want to start xmms with following php script.
<?php
echo shell_exec("xmms");
?>
It works only from the shell too.
I've played with apache configuration so much now that I really dont know what to try.
I tried $xhost + && export DISPLAY=:0.0
In the http.conf I have these
SetEnv DISPLAY :0.0 SetEnv XAUTHORITY /home/OpenGL/.Xauthority
So my problem seems to be this:
How can I make apache execute php script with all privileges that the http user has, including the environment?
Additional information:
HTTP is in video and users groups and has a login shell(bash).
I can login as http and execute scripts with no problem and can run GUI programs which show up on display 0.
It seems that apache does not provide the appropriate environment for the script.
I read about some difference between CLI/CGI but cant run xmms with php-cgi too...
Any ideas for additional configuration?
Regards
Sounds bit hazard, but basically you can add even export DISPLAY=:0.0 to apache start-up script (like in Linux /etc/init.d/httpd or apache depending distro).
And "xhost +" need to be run on account which is connected to local X server as user, though I'm only wondering how it will work as php script should only live while apache http request is on-going.
Edit:
Is this is kind of application launcher?, you can spawn this with exec("nohub /usr/bin/php script.php &"); .. now apache should be released and php should continue working in background.
In your console, allow everyone to use the X server:
xhost +
In your PHP script, set the DISPLAY variable while executing the commands:
DISPLAY=:0 glxgears 2>&1