BugHunterUK
BugHunterUK

Reputation: 8948

PHP built in server unable to load env variables

First I run the following script to set the environment variable:

bin/env.sh

#!/bin/bash

export JWT_SECRET="29dvqfmREKeOgBhGtTogK1pAi+2/x45hKzxONHetwFM="
export DB_HOST=127.0.0.1
export DB_NAME=myapp
export DB_USER=user
export DB_PASS=password
export DB_PORT=3306

bin/env.sh

Then I run the next script in the same terminal to start development server:

bin/dev.sh

#!/bin/bash

php -d variables_order=EGPCS -S localhost:5001 -t ./public

bin/dev.sh

The server starts, but when I echo getenv('DB_USER') it's blank.

The thing is, if I put php -d variables_order=EGPCS -S localhost:5001 -t ./public at the foot of env.sh it works.

Why does it work if it's in the same script, but doesn't otherwise? Both scripts are being ran from the same terminal

Upvotes: 0

Views: 489

Answers (2)

Inian
Inian

Reputation: 85600

The problem you are facing is none of the variables you defined in bin/env.sh is available in the current shell in which you are running the development server. Hence, you need to add a line

source bin/env.sh

at beginning of the bin/dev.sh to make the variables available in the current session.

There is a built-in shell built-in source available just for that. On sourcing the file, you are actually executing commands from filename in the current shell environment.

Remember sourcing is different from running a script which "executes" the script in a new shell than the shell originally invoked from.

To explain better with an example:-

Consider script.sh with following content:

#!/bin/bash

echo "foo: "$(env | grep FOO)
export FOO=foo
echo "foo: "$(env | grep FOO)

Before we execute the script first we check the current environment:

$ env | grep FOO

The variable FOO is not defined. On executing the file

$ ./script.sh
foo:
foo: FOO=foo

Check the environment again:

$ env | grep FOO

The variable FOO is not set.

The script output clearly shows that the variable was set. The check post running the script showed that the variable is not set because the changes were made in a new shell. The current shell spawned a new shell to run the script and all the exported variables are available only till the life time of that spawned shell. After the script terminates the new shell is destroyed. All changes to the environment in the new shell are destroyed with the new shell. Only the output text is printed in the current shell.

Now we source the file:

$ source script.sh
foo:
foo: FOO=foo

$ env | grep FOO
FOO=foo

You can see now the variable FOO is set.

Upvotes: 1

ccarton
ccarton

Reputation: 3666

The export command makes variables available to sub-shells, it doesn't add them to the parent environment. Use source if you want to run a script to update the current environment.

Upvotes: 0

Related Questions