6

I usually source a *.sh file in a bash terminal on linux like this

. ./myscript.sh

before running a command line PHP script so i can access exported environment variables using PHP's $_SERVER super global.

Is it possible to source the sh file from within the PHP script itself to then access the variables it exports?

I've tried all sorts with no success. I've tried

system('. ./myscript.sh')
system('sh ./myscript.sh')

exec('. ./myscript.sh')
exec('sh ./myscript.sh')

shell_exec('. ./myscript.sh')
shell_exec('sh ./myscript.sh')

using these, the exported vars do not appear in $_SERVER.

Any ideas?

Gary Willoughby
  • 50,926
  • 41
  • 133
  • 199

3 Answers3

4

Your variables aren't available because the shell that they existed in has exited. You need to execute PHP from within the same shell in order to get its vars.

Either edit myscript.sh to launch the PHP script after setting the vars:

export VAR1=1
export VAR2=2
php -f /path/to/script.php

Or write another wrapper script that sources your file and then launches PHP from the same shell:

. ./myscript.sh
php -f /path/to/script.php

Edit: Or just run your script like this:

. ./myscript.sh && php -f /path/to/script.php
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
1

First of all, if you're creating a commandline php script, I don't know how many env variables you'll get on your $_SERVER array.

You might want to try to use the getenv() function: http://www.php.net/manual/en/function.getenv.php

Also, to source your file, have you tried doing?:

exec('source ./myscript.sh')

Let me know if any of that helps!

Deleteman
  • 8,500
  • 6
  • 25
  • 39
1

Sourcing a file into a shell, such as bash, requires that shell be running and it just reads in that file and interprets it. When you run php from the shells command line it forks a separate process that inherits the environment. When that process ends it throws away the memory footprint of the executable including the environment.

As to getting PHP to execute a script, it will do the same - create separatete process for bash (for example) and get that process to read in the script, interpret it, follows its commands to the letter then when it comes to an end the process will terminate along with thenvironmentalal changes that it has made.

So a possible solution for this is to do the following.

  1. The PHP script needs to determine its location in the file system.
  2. The PHP script needs to determine if it is calling it self.
  3. If the script is NOT calling itself, run a bash script to set up the environment, add an extra environment variable to enable it to determine it not to go down this route again and execulte itselt. Perhaps use something like popen to fire into bash the commands source, export, exec php
  4. If the scipt is calling itself, just execute

Seems a lot of hassle. Just write a script to set up the environment and then fire off PHP.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127