[PHP] About environment variables

cereal 0 Tallied Votes 279 Views Share

Simple Advice

This is just a reminder. When setting environment variables through .htaccess, CLI or dotenv use filter_var() to evaluate a boolean. For example, start the built-in PHP server with these variables:

DEBUG=FALSE LOG=TRUE SMS=1 SMTP=0 CONNECT=yes BACKUP=no php -d variables_order=EGPCS -S localhost:8000

And then test through boolval(): if you forget to use 1 and 0, then something can go wrong as the variable is evaluated like a string and will always return TRUE. By using filter_var(), with the appropriate filter to validate boolean, you get more flexibility as it:

returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.

Docs: http://php.net/manual/en/filter.filters.validate.php

# environment variable from inside the script
$_ENV['TEST'] = FALSE;

# boolval()
var_dump(boolval($_ENV['DEBUG']));   # bool(true)
var_dump(boolval($_ENV['LOG']));     # bool(true)
var_dump(boolval($_ENV['SMS']));     # bool(true)
var_dump(boolval($_ENV['SMTP']));    # bool(false)
var_dump(boolval($_ENV['CONNECT'])); # bool(true)
var_dump(boolval($_ENV['BACKUP']));  # bool(true)
var_dump(boolval($_ENV['TEST']));    # bool(false)

# filter_var()
var_dump(filter_var($_ENV['DEBUG']  , FILTER_VALIDATE_BOOLEAN)); # bool(false) <-- diff
var_dump(filter_var($_ENV['FOO']    , FILTER_VALIDATE_BOOLEAN)); # bool(true)
var_dump(filter_var($_ENV['SMS']    , FILTER_VALIDATE_BOOLEAN)); # bool(true)
var_dump(filter_var($_ENV['SMTP']   , FILTER_VALIDATE_BOOLEAN)); # bool(false)
var_dump(filter_var($_ENV['CONNECT'], FILTER_VALIDATE_BOOLEAN)); # bool(true)
var_dump(filter_var($_ENV['BACKUP'] , FILTER_VALIDATE_BOOLEAN)); # bool(false) <-- diff
var_dump(filter_var($_ENV['TEST']   , FILTER_VALIDATE_BOOLEAN)); # bool(false)