Brad Koch
Brad Koch

Reputation: 20297

Setting environment variables with the built-in PHP web server

PHP 5.4 supports a built-in web server for development purposes. The app we are developing is configured via environment variables.

With Apache you'd do this:

SetEnv FAVORITE_COLOR white

With the normal CLI you can do this:

$ export FAVORITE_COLOR=black
$ php -a
php > echo $_SERVER['FAVORITE_COLOR'];

Is there a way to set these variables for the built-in web server?

Upvotes: 36

Views: 15899

Answers (3)

w. Patrick Gale
w. Patrick Gale

Reputation: 2337

I use Window DOS to start the PHP server. I store my server startup commands in a text batch file (.bat) to save me from having to select and copy all of the commands at once and paste it into the DOS terminal (note the last blank line that I copy as well so the PHP server will automatically start when I paste the commands into DOS, otherwise I would need to manually use the Enter key to start the server).

Q:
cd Q:\GitLabRepos\myapps\test1
set APPLICATION_TITLE=My testing application with this first env variable
set SOME_OTHER_ENV_VAR2={"myJsonElement":"some value"}
E:\PHP8\php.exe -d variables_order=E -S localhost:8000 -c php.ini

The commands above explained:

The first line Q: changes to the drive where my code resides. The second line cd Q:\GitLabRepos\myapps\test1 changes directories to my root PHP application code (which is where I want to start the PHP server). Next I set some environment variables on lines 3 and 4. Then finally I start the PHP server with the -d variables_order=E parameter so I can use either $_ENV or getenv() to retrieve the environment variable values in my PHP code (eg. $_ENV['APPLICATION_TITLE'] or getenv('APPLICATION_TITLE')). If you exclude -d variables_order=E from the server startup command then you can only use getenv() to access the environment variables. I use the -c php.ini parameter to load additional PHP settings from a php.ini file but this can be excluded for simple server setup.

Then if I have a Q:\GitLabRepos\myapps\test1\index.php script with the following code:

<?php
echo getenv('APPLICATION_TITLE').'---'.$_ENV['APPLICATION_TITLE'].'...'.getenv('SOME_OTHER_ENV_VAR2');
?>

If I visit localhost:8000 in a web browser I should see

My testing application with this first env variable---My testing application with this first env variable...{"myJsonElement":"some value"}.

Upvotes: 1

F&#225;bio Paiva
F&#225;bio Paiva

Reputation: 569

On Windows:

SET FOO=BAR
php -s localhost:9090

Upvotes: -4

mcuadros
mcuadros

Reputation: 4144

Looks like E is excluded from variable_order setting running the built-in server. If you add the E to the variable_order setting, it works:

test.php

<?php
var_dump($_ENV['FOO']);

shell:

FOO=BAR php -d variables_order=EGPCS -S localhost:9090 /tmp/test.php

output:

string 'BAR' (length=3)

Tested on PHP 5.4.12

Upvotes: 54

Related Questions