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


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

. ./

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('. ./')
system('sh ./')

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

shell_exec('. ./')
shell_exec('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 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:

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

Edit: Or just run your script like this:

. ./ && php -f /path/to/script.php