Categories
PHP programming

Read .env files with PHP

The following code is written for Yii2 framework, but except for the first line of the function that fetches the path to the root directory of project, it works with other PHP frameworks or without a framework.

function read($param){
    $path = Yii::getAlias('@app'."/../");
    $envData = [];
    if (!is_readable($path . "/.env" )) {
        //
    } else {
        $lines = file($path."/.env", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        foreach ($lines as $key => $value) {
            $explode = explode("=", $value);
            if(array_key_exists(1, $explode)){
                $envData[$explode[0]] = $explode[1];
            }
        }
        
    }

    

    if(array_key_exists($param, $envData)){
        return $envData[$param];
    } else {
        return NULL;
    }
}