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?
PHP allows us to use the shell_exec(); function to deal with shell files. However, if your OS is Windows, you should consider using popen() and pclose() functions because the pipes are executed in text mode, which usually keeps it from binary outputs. We will implement two scripts in our shell.
The source Command The built-in bash source command reads and executes the content of a file. If the sourced file is a bash script, the overall effect comes down to running it. We may use this command either in a terminal or inside a bash script.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With