Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to source a *.sh file using PHP CLI and access exported Env vars in the PHP script?

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?

like image 512
Gary Willoughby Avatar asked Apr 24 '12 17:04

Gary Willoughby


People also ask

Can PHP run a shell script?

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.

What is bash source command?

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.


2 Answers

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
like image 103
Alex Howansky Avatar answered Nov 06 '22 06:11

Alex Howansky


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!

like image 32
Deleteman Avatar answered Nov 06 '22 05:11

Deleteman