Use Default Value for INI Environment Variables in PHP 8.3

Use Default Value for INI Environment Variables in PHP 8.3

PHP provides the capability to replace PHP INI values using environment variables through the utilization of PHP's string interpolation syntax. This feature allows for dynamic configuration by seamlessly incorporating environment variables directly into PHP scripts. Before PHP 8.3, in cases where the provided environment variable is not present, the INI parser defaults to using an empty string.

Since PHP 8.3, it is possible to set the default INI variable value if the environment variable is not defined.

In the following code snippet, the PHP configuration file (php.ini) is used to define the memory_limit setting. The setting is assigned a value based on an environment variable, PHP_MEMORY_LIMIT, but with a fallback option using the syntax ${ENV_VAR:-VALUE}.

Therefore, the memory_limit setting in php.ini will be set to the value of the PHP_MEMORY_LIMIT environment variable if it is defined. If the PHP_MEMORY_LIMIT variable is not set, the memory_limit will default to 2048M.

<?php

// php.ini contains the following settings:
// memory_limit = ${PHP_MEMORY_LIMIT:-2048M}

echo ini_get('memory_limit'); // Value of PHP_MEMORY_LIMIT or 2048M

The syntax for specifying fallback values is applicable across all PHP functions responsible for retrieving, parsing, and configuring INI settings. This includes: ini_get, ini_get_all, ini_set, get_cfg_var, parse_ini_string, and parse_ini_file.

<?php

$ini = 'redis.host = 127.0.0.1:${REDIS_PORT:-6379}';

$content = parse_ini_string($ini);
echo $content['redis.host']; // 127.0.0.1: with value of REDIS_PORT or 6379

Leave a Comment

Cancel reply

Your email address will not be published.