Is it possible to create a * .sh file using PHP CLI and access Envvars exported in the PHP script?

advertisements

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?


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