How to set .env values in laravel programmatically on the fly - php

I have a custom CMS that I am writing from scratch in Laravel and want to set env values i.e. database details, mailer details, general configuration, etc from controller once the user sets up and want to give user the flexibility to change them on the go using the GUI that I am making.
So my question is how do I write the values received from user to the .env file as an when I need from the controller.
And is it a good idea to build the .env file on the go or is there any other way around it?

Since Laravel uses config files to access and store .env data, you can set this data on the fly with config() method:
config(['database.connections.mysql.host' => '127.0.0.1']);
To get this data use config():
config('database.connections.mysql.host')
To set configuration values at runtime, pass an array to the config helper
https://laravel.com/docs/5.3/configuration#accessing-configuration-values

Watch out! Not all variables in the laravel .env are stored in the config environment.
To overwrite real .env content use simply:
putenv ("CUSTOM_VARIABLE=hero");
To read as usual, env('CUSTOM_VARIABLE') or env('CUSTOM_VARIABLE', 'devault')
NOTE: Depending on which part of your app uses the env setting, you may need to set the variable early by placing it into your index.php or bootstrap.php file. Setting it in your app service provider may be too late for some packages/uses of the env settings.

More simplified:
public function putPermanentEnv($key, $value)
{
$path = app()->environmentFilePath();
$escaped = preg_quote('='.env($key), '/');
file_put_contents($path, preg_replace(
"/^{$key}{$escaped}/m",
"{$key}={$value}",
file_get_contents($path)
));
}
or as helper:
if ( ! function_exists('put_permanent_env'))
{
function put_permanent_env($key, $value)
{
$path = app()->environmentFilePath();
$escaped = preg_quote('='.env($key), '/');
file_put_contents($path, preg_replace(
"/^{$key}{$escaped}/m",
"{$key}={$value}",
file_get_contents($path)
));
}
}

Based on josh's answer. I needed a way to replace the value of a key inside the .env file.
But unlike josh's answer, I did not want to depend on knowing the current value or the current value being accessible in a config file at all.
Since my goal is to replace values that are used by Laravel Envoy which doesn't use a config file at all but instead uses the .env file directly.
Here's my take on it:
public function setEnvironmentValue($envKey, $envValue)
{
$envFile = app()->environmentFilePath();
$str = file_get_contents($envFile);
$oldValue = strtok($str, "{$envKey}=");
$str = str_replace("{$envKey}={$oldValue}", "{$envKey}={$envValue}\n", $str);
$fp = fopen($envFile, 'w');
fwrite($fp, $str);
fclose($fp);
}
Usage:
$this->setEnvironmentValue('DEPLOY_SERVER', 'forge#122.11.244.10');

Based on totymedli's answer.
Where it is required to change multiple enviroment variable values at once, you could pass an array (key->value). Any key not present previously will be added and a bool is returned so you can test for success.
public function setEnvironmentValue(array $values)
{
$envFile = app()->environmentFilePath();
$str = file_get_contents($envFile);
if (count($values) > 0) {
foreach ($values as $envKey => $envValue) {
$str .= "\n"; // In case the searched variable is in the last line without \n
$keyPosition = strpos($str, "{$envKey}=");
$endOfLinePosition = strpos($str, "\n", $keyPosition);
$oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition);
// If key does not exist, add it
if (!$keyPosition || !$endOfLinePosition || !$oldLine) {
$str .= "{$envKey}={$envValue}\n";
} else {
$str = str_replace($oldLine, "{$envKey}={$envValue}", $str);
}
}
}
$str = substr($str, 0, -1);
if (!file_put_contents($envFile, $str)) return false;
return true;
}

#more simple way to cover .env you can do like this
$_ENV['key'] = 'value';

tl;dr
Based on vesperknight's answer I created a solution that doesn't use strtok or env().
private function setEnvironmentValue($envKey, $envValue)
{
$envFile = app()->environmentFilePath();
$str = file_get_contents($envFile);
$str .= "\n"; // In case the searched variable is in the last line without \n
$keyPosition = strpos($str, "{$envKey}=");
$endOfLinePosition = strpos($str, PHP_EOL, $keyPosition);
$oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition);
$str = str_replace($oldLine, "{$envKey}={$envValue}", $str);
$str = substr($str, 0, -1);
$fp = fopen($envFile, 'w');
fwrite($fp, $str);
fclose($fp);
}
Explanation
This doesn't use strtok that might not work for some people, or env() that won't work with double-quoted .env variables which are evaluated and also interpolates embedded variables
KEY="Something with spaces or variables ${KEY2}"

If you don't need to save your changes to .env file, you could simply user this code :
\Illuminate\Support\Env::getRepository()->set('APP_NAME','New app name');

In the event that you want these settings to be persisted to the environment file so they be loaded again later (even if the configuration is cached), you can use a function like this. I'll put the security caveat in there, that calls to a method like this should be gaurded tightly and user input should be sanitized properly.
private function setEnvironmentValue($environmentName, $configKey, $newValue) {
file_put_contents(App::environmentFilePath(), str_replace(
$environmentName . '=' . Config::get($configKey),
$environmentName . '=' . $newValue,
file_get_contents(App::environmentFilePath())
));
Config::set($configKey, $newValue);
// Reload the cached config
if (file_exists(App::getCachedConfigPath())) {
Artisan::call("config:cache");
}
}
An example of it's use would be;
$this->setEnvironmentValue('APP_LOG_LEVEL', 'app.log_level', 'debug');
$environmentName is the key in the environment file (example.. APP_LOG_LEVEL)
$configKey is the key used to access the configuration at runtime (example.. app.log_level (tinker config('app.log_level')).
$newValue is of course the new value you wish to persist.

If you want to change it temporarily (e.g. for a test), this should work for Laravel 8:
<?php
namespace App\Helpers;
use Dotenv\Repository\Adapter\ImmutableWriter;
use Dotenv\Repository\AdapterRepository;
use Illuminate\Support\Env;
class DynamicEnvironment
{
public static function set(string $key, string $value)
{
$closure_adapter = \Closure::bind(function &(AdapterRepository $class) {
$closure_writer = \Closure::bind(function &(ImmutableWriter $class) {
return $class->writer;
}, null, ImmutableWriter::class);
return $closure_writer($class->writer);
}, null, AdapterRepository::class);
return $closure_adapter(Env::getRepository())->write($key, $value);
}
}
Usage:
App\Helpers\DynamicEnvironment::set("key_name", "value");

Based on totymedli's answer and Oluwafisayo's answer.
I set a little modification to change the .env file, It works too fine in Laravel 5.8, but when after I changed it the .env file was modificated I could see variables did not change after I restart with php artisan serve, so I tried to clear cache and others but I can not see a solution.
public function setEnvironmentValue(array $values)
{
$envFile = app()->environmentFilePath();
$str = file_get_contents($envFile);
$str .= "\r\n";
if (count($values) > 0) {
foreach ($values as $envKey => $envValue) {
$keyPosition = strpos($str, "$envKey=");
$endOfLinePosition = strpos($str, "\n", $keyPosition);
$oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition);
if (is_bool($keyPosition) && $keyPosition === false) {
// variable doesnot exist
$str .= "$envKey=$envValue";
$str .= "\r\n";
} else {
// variable exist
$str = str_replace($oldLine, "$envKey=$envValue", $str);
}
}
}
$str = substr($str, 0, -1);
if (!file_put_contents($envFile, $str)) {
return false;
}
app()->loadEnvironmentFrom($envFile);
return true;
}
So it rewrites correctly the .env file with the funtion setEnvironmentValue, but How can Laravel reload the new .env without to restart the system?
I was looking information about that and I found
Artisan::call('cache:clear');
but in local it does not work! for me, but when I uploaded the code and test in my serve it works to fine.
I tested it in Larave 5.8 and worked in my serve...
This could be a tip when you have a variable with more than one word and separetly with a space, the solution i did
public function update($variable, $value)
{
if ($variable == "APP_NAME" || $variable == "MAIL_FROM_NAME") {
$value = "\"$value\"";
}
$values = array(
$variable=>$value
);
$this->setEnvironmentValue($values);
Artisan::call('config:clear');
return true;
}

Tailor Otwell generate the laravel application key and set its value using this code (code modified for example purpose):
$escaped = preg_quote('='.config('broadcasting.default'), '/');
file_put_contents(app()->environmentFilePath(), preg_replace("/^BROADCAST_DRIVER{$escaped}/m", 'BROADCAST_DRIVER='.'pusher',
file_get_contents(app()->environmentFilePath())
));
You can find the code in the key generation class:
Illuminate\Foundation\Console\KeyGenerateCommand

you can use this package
https://github.com/ImLiam/laravel-env-set-command
then use Artisan Facade to call artisan commands ex:
Artisan::call('php artisan env:set app_name Example')

PHP 8 solution
This solution is using env() so should only be run when the configuration is NOT cached.
/**
* #param string $key
* #param string $value
*/
protected function setEnvValue(string $key, string $value)
{
$path = app()->environmentFilePath();
$env = file_get_contents($path);
$old_value = env($key);
if (!str_contains($env, $key.'=')) {
$env .= sprintf("%s=%s\n", $key, $value);
} else if ($old_value) {
$env = str_replace(sprintf('%s=%s', $key, $old_value), sprintf('%s=%s', $key, $value), $env);
} else {
$env = str_replace(sprintf('%s=', $key), sprintf('%s=%s',$key, $value), $env);
}
file_put_contents($path, $env);
}

this function update new value of existing key or add new key=value to end of file
function setEnv($envKey, $envValue) {
$path = app()->environmentFilePath();
$escaped = preg_quote('='.env($envKey), '/');
//update value of existing key
file_put_contents($path, preg_replace(
"/^{$envKey}{$escaped}/m",
"{$envKey}={$envValue}",
file_get_contents($path)
));
//if key not exist append key=value to end of file
$fp = fopen($path, "r");
$content = fread($fp, filesize($path));
fclose($fp);
if (strpos($content, $envKey .'=' . $envValue) == false && strpos($content, $envKey .'=' . '\"'.$envValue.'\"') == false){
file_put_contents($path, $content. "\n". $envKey .'=' . $envValue);
}
}

$envFile = app()->environmentFilePath();
$_ENV['APP_NAME'] = "New Project Name";
$txt= "";
foreach ($_ENV as $key => $value) {
$txt .= $key."=".$value."\n"."\n";
}
file_put_contents($envFile,$txt);

This solution can create, replace and save the values given in the .env file.
I created this to be used in a command package:install to add the .env key-value pairs automatically to the .env file.
/**
* Set .env key-value pair
*
* #param array $keyPairs Desired key name
* #return void
*/
public function saveArrayToEnv(array $keyPairs)
{
$envFile = app()->environmentFilePath();
$newEnv = file_get_contents($envFile);
$newlyInserted = false;
foreach ($keyPairs as $key => $value) {
// Make sure key is uppercase (can be left out)
$key = Str::upper($key);
if (str_contains($newEnv, "$key=")) {
// If key exists, replace value
$newEnv = preg_replace("/$key=(.*)\n/", "$key=$value\n", $newEnv);
} else {
// Check if spacing is correct
if (!str_ends_with($newEnv, "\n\n") && !$newlyInserted) {
$newEnv .= str_ends_with($newEnv, "\n") ? "\n" : "\n\n";
$newlyInserted = true;
}
// Append new
$newEnv .= "$key=$value\n";
}
}
$fp = fopen($envFile, 'w');
fwrite($fp, $newEnv);
fclose($fp);
}
You pass it an associative array:
$keyPairs = [
'KEY' => 'VALUE',
'API_KEY' => 'XXXXXX-XXXXXX-XXXXX'
]
And it will add them or replace they values of the given keys with the given values.
Of course there is room for improvement like checking if the array is actually an associative array. But this will do for hard coded stuff in things like Laravel command classes.

This solution builds upon the one provided by Elias Tutungi, it accepts multiple value changes and uses a Laravel Collection because foreach's are gross
function set_environment_value($values = [])
{
$path = app()->environmentFilePath();
collect($values)->map(function ($value, $key) use ($path) {
$escaped = preg_quote('='.env($key), '/');
file_put_contents($path, preg_replace(
"/^{$key}{$escaped}/m",
"{$key}={$value}",
file_get_contents($path)
));
});
return true;
}

You can use this custom method i located from internet ,
/**
* Calls the method
*/
public function something(){
// some code
$env_update = $this->changeEnv([
'DB_DATABASE' => 'new_db_name',
'DB_USERNAME' => 'new_db_user',
'DB_HOST' => 'new_db_host'
]);
if($env_update){
// Do something
} else {
// Do something else
}
// more code
}
protected function changeEnv($data = array()){
if(count($data) > 0){
// Read .env-file
$env = file_get_contents(base_path() . '/.env');
// Split string on every " " and write into array
$env = preg_split('/\s+/', $env);;
// Loop through given data
foreach((array)$data as $key => $value){
// Loop through .env-data
foreach($env as $env_key => $env_value){
// Turn the value into an array and stop after the first split
// So it's not possible to split e.g. the App-Key by accident
$entry = explode("=", $env_value, 2);
// Check, if new key fits the actual .env-key
if($entry[0] == $key){
// If yes, overwrite it with the new one
$env[$env_key] = $key . "=" . $value;
} else {
// If not, keep the old one
$env[$env_key] = $env_value;
}
}
}
// Turn the array back to an String
$env = implode("\n", $env);
// And overwrite the .env with the new data
file_put_contents(base_path() . '/.env', $env);
return true;
} else {
return false;
}
}

use the function below to change values in .env file laravel
public static function envUpdate($key, $value)
{
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents($path, str_replace(
$key . '=' . env($key), $key . '=' . $value, file_get_contents($path)
));
}
}

Replace single value in .env file function:
/**
* #param string $key
* #param string $value
* #param null $env_path
*/
function set_env(string $key, string $value, $env_path = null)
{
$value = preg_replace('/\s+/', '', $value); //replace special ch
$key = strtoupper($key); //force upper for security
$env = file_get_contents(isset($env_path) ? $env_path : base_path('.env')); //fet .env file
$env = str_replace("$key=" . env($key), "$key=" . $value, $env); //replace value
/** Save file eith new content */
$env = file_put_contents(isset($env_path) ? $env_path : base_path('.env'), $env);
}
Example to local (laravel) use: set_env('APP_VERSION', 1.8).
Example to use custom path: set_env('APP_VERSION', 1.8, $envfilepath).

Related

How i can change .env variables in Laravel 6.0 by controller?

I am making a system on Laravel where i want to give rights to admin to change some .env variables like mail settings(server or port) etc. How can i do it?
I have created a method changeEnv for same:
public function changeEnv($data = array()){
if(count($data) > 0){
// Read .env-file
$env = file_get_contents(base_path() . '/.env');
// Split string on every " " and write into array
$env = preg_split('/\s+/', $env);;
// Loop through given data
foreach((array)$data as $key => $value){
// Loop through .env-data
foreach($env as $env_key => $env_value){
// Turn the value into an array and stop after the first split
// So it's not possible to split e.g. the App-Key by accident
$entry = explode("=", $env_value, 2);
// Check, if new key fits the actual .env-key
if($entry[0] == $key){
// If yes, overwrite it with the new one
$env[$env_key] = $key . "=" . $value;
} else {
// If not, keep the old one
$env[$env_key] = $env_value;
}
}
}
// Turn the array back to an String
$env = implode("\n", $env);
// And overwrite the .env with the new data
file_put_contents(base_path() . '/.env', $env);
return true;
} else {
return false;
}
}
usage :
$this->changeEnv(['lastEvaluatedKeyAU' => 'randomID-or-randomString']);

PHP function to edit configuration file

I'm looking for a PHP function that I can use to edit key/value pairs in a text file.
What I want to do (PHP):
changeValue(key, bar);
and have in setings.txt:
key = foo
key2 =foo2
Change to:
key = bar
key2 = foo2
What I got so far (not working):
function changeValue($input) {
$file = file_get_contents('/path/to/settings.txt');
preg_match('/\b$input[0]\b/', $file, $matches);
$file = str_replace($matches[1], $input, $file);
file_put_contents('/path/to/settings.txt', $file);
}
How to update an ini file with php? got me started. I read many other questions but I couldn't get it working.
I would use JSON with at least the JSON_PRETTY_PRINT option to write and json_decode() to read.
// read file into an array of key => foo
$settings = json_decode(file_get_contents('/path/to/settings.txt'), true);
// write array to file as JSON
file_put_contents('/path/to/settings.txt', json_encode($settings, JSON_PRETTY_PRINT));
Which will create a file such as:
{
"key": "foo",
"key2": "bar",
"key3": 1
}
Another possibility is var_export() using a similar approach, or another simple example for what you're asking:
// read file into an array of key => foo
$string = implode('&', file('/path/to/settings.txt', FILE_IGNORE_NEW_LINES));
parse_str($string, $settings);
// write array to file as key=foo
$data = implode("\n", $settings);
file_put_contents('/path/to/settings.txt', $data);
So read in the file, change the setting $setting['key'] = 'bar'; and then write it out.
Instead of using file_get_contents use file, this reads each line in as an array.
Under you see working code. Had a little problem with write array added more breaks but not sure why.
changeValue("key", "test123");
function changeValue($key, $value)
{
//get each line as an array.
$file = file("test.txt");
//go through the array, the value is references so when it is changed the value in the array is changed.
foreach($file as &$val)
{
//check if the string line contains the current key. If it contains the key replace the value. substr takes everything before "=" so not to run if the value is the same as the key.
if(strpos(substr($val, 0, strpos($val, "=")), $key) !== false)
{
//clear the string
$val = substr($val, 0, strpos($val, "="));
//add the value
$val .= "= " . $value;
}
}
//send the changed array writeArray();
writeArray($file);
}
function writeArray($array)
{
$str = "";
foreach($array as $value)
{
$str .= $value . "\n";
}
//write the array.
file_put_contents('test.txt', $str);
}
?>

php change value of multidimensional array

I got a problem.
I make a function to update my config.json file.
The problem is, my config.json is a multdimensional array. To get a value of a key i use this function:
public function read($key)
{
$read = explode('.', $key);
$config = $this->config;
foreach ($read as $key) {
if (array_key_exists($key, $config)) {
$config = $config[$key];
}
}
return $config;
}
I also made a function to update a key. But the problem is if i make update('database.host', 'new value'); it dont updates only that key but it overrides the whole array.
This is my update function
public function update($key, $value)
{
$read = explode('.', $key);
$config = $this->config;
foreach ($read as $key) {
if (array_key_exists($key, $config)) {
if ($key === end($read)) {
$config[$key] = $value;
}
$config = $config[$key];
}
}
print_r( $config );
}
my config.json looks like this:
{
"database": {
"host": "want to update with new value",
"user": "root",
"pass": "1234",
"name": "dev"
},
some more content...
}
I have a working function but thats not really good. I know that the max of the indexes only can be three, so I count the exploded $key and update the value:
public function update($key, $value)
{
$read = explode('.', $key);
$count = count($read);
if ($count === 1) {
$this->config[$read[0]] = $value;
} elseif ($count === 2) {
$this->config[$read[0]][$read[1]] = $value;
} elseif ($count === 3) {
$this->config[$read[0]][$read[1]][$read[3]] = $value;
}
print_r($this->config);
}
Just to know: the variable $this->config is my config.json parsed to an php array, so nothing wrong with this :)
After I had read your question better I now understand what you want, and your read function, though not very clear, works fine.
Your update can be improved though by using assign by reference & to loop over your indexes and assign the new value to the correct element of the array.
What the below code does is assign the complete config object to a temporary variable newconfig using call by reference, this means that whenever we change the newconfig variable we also change the this->config variable.
Using this "trick" multiple times we can in the end assign the new value to the newconfig variable and because of the call by reference assignments the correct element of the this->config object should be updated.
public function update($key, $value)
{
$read = explode('.', $key);
$count = count($read);
$newconfig = &$this->config; //assign a temp config variable to work with
foreach($read as $key){
//update the newconfig variable by reference to a part of the original object till we have the part of the config object we want to change.
$newconfig = &$newconfig[$key];
}
$newconfig = $value;
print_r($this->config);
}
You can try something like this:
public function update($path, $value)
{
array_replace_recursive(
$this->config,
$this->pathToArray("$path.$value")
);
var_dump($this->config);
}
protected function pathToArray($path)
{
$pos = strpos($path, '.');
if ($pos === false) {
return $path;
}
$key = substr($path, 0, $pos);
$path = substr($path, $pos + 1);
return array(
$key => $this->pathToArray($path),
);
}
Please note that you can improve it to accept all data types for value, not only scalar ones

Creating a function that takes arguments and passes variables

I am creating a script that will locate a field in a text file and get the value that I need.
First used the file() function to load my txt into an array by line.
Then I use explode() to create an array for the strings on a selected line.
I assign labels to the array's to describe a $Key and a $Value.
$line = file($myFile);
$arg = 3
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
This works fine but that is a lot of code to have to do over and over again for everything I want to get out of the txt file. So I wanted to create a function that I could call with an argument that would return the value of $key and $val. And this is where I am failing:
<?php
/**
* #author Jason Moore
* #copyright 2014
*/
global $line;
$key = '';
$val = '';
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$arg = 3;
$Character_Name = 3
function get_plr_data2($arg){
global $key;
global $val;
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return;
}
get_plr_data2($Character_Name);
echo "This character's ",$key,' is ',$val;
?>
I thought that I covered the scope with setting the values in the main and then setting them a global within the function. I feel like I am close but I am just missing something.
I feel like there should be something like return $key,$val; but that doesn't work. I could return an Array but then I would end up typing just as much code to the the info out of the array.
I am missing something with the function and the function argument to. I would like to pass and argument example : get_plr_data2($Character_Name); the argument identifies the line that we are getting the data from.
Any help with this would be more than appreciated.
::Updated::
Thanks to the answers I got past passing the Array.
But my problem is depending on the arguments I put in get_plr_data2($arg) the number of values differ.
I figured that I could just set the Max of num values I could get but this doesn't work at all of course because I end up with undefined offsets instead.
$a = $cdata[0];$b = $cdata[1];$c = $cdata[2];
$d = $cdata[3];$e = $cdata[4];$f = $cdata[5];
$g = $cdata[6];$h = $cdata[7];$i = $cdata[8];
$j = $cdata[9];$k = $cdata[10];$l = $cdata[11];
return array($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l);
Now I am thinking that I can use the count function myCount = count($c); to either amend or add more values creating the offsets I need. Or a better option is if there was a way I could generate the return array(), so that it would could the number of values given for array and return all the values needed. I think that maybe I am just making this a whole lot more difficult than it is.
Thanks again for all the help and suggestions
function get_plr_data2($arg){
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return array($key,$val);
}
Using:
list($key,$val) = get_plr_data2(SOME_ARG);
you can do this in 2 way
you can return both values in an array
function get_plr_data2($arg){
/* do what you have to do */
$output=array();
$output['key'] =$key;
$output['value']= $value;
return $output;
}
and use the array in your main function
you can use reference so that you can return multiple values
function get_plr_data2($arg,&$key,&$val){
/* do job */
}
//use the function as
$key='';
$val='';
get_plr_data2($arg,$key,$val);
what ever you do to $key in function it will affect the main functions $key
I was over thinking it. Thanks for all they help guys. this is what I finally came up with thanks to your guidance:
<?php
$ch_file = "Thor";
$ch_name = 3;
$ch_lvl = 4;
$ch_clss = 15;
list($a,$b)= get_char($ch_file,$ch_name);//
Echo $a,': ',$b; // Out Puts values from the $cdata array.
function get_char($file,$data){
$myFile = $file.".txt";
$line = file($myFile);
$cdata = preg_split('/\s+/', trim($line[$data]));
return $cdata;
}
Brand new to this community, thanks for all the patience.

Dynamically update variables into an existing file?

I'm trying to build a small CMS using CodeIgniter, and I need to be able to dynamically update some variables within the application/config.php
So far I did:
private function update_file ($file, $var, $var_name) {
$start_tag = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n";
if (file_exists($file)) {
require_once ($file);
$updated_array = array_merge($$var_name, $var);
$data = $start_tag."\$".$var_name." = ".var_export($updated_array, true).";";
file_put_contents($file, $data);
} else {
return false;
}
}
Everything works just fine! The result in the config.php file will be:
<?php ...;
$config = array (
'base_url' => '',
...
...
);
But what if I would like to maintain the original config.php file format with comments, spaces and
separated declared $config['key'] = 'value' ... ?
Is that possible ?
EDIT:
Thank you for your answers, very precious.
I found a slightly different solution for my needs, performing a preg_replace on the return of file_get_contents() and then write back on the file the new resulting string. File maintains the exact original clean format.
private function update_file ($file, $var, $var_name) {
if (file_exists($file)) {
require_once ($file);
$contents = file_get_contents($file);
$updated_array = array_merge($$var_name, $var);
$search = array();
$replace = array();
foreach($$var_name as $key => $val) {
$pattern = '/\$'.$var_name.'\[\\\''.$key.'\\\'\]\s+=\s+[^\;]+/';
$replace_string = "\$".$var_name."['".$key."'] = ".var_export($updated_array[$key], true);
array_push($search, $pattern);
array_push($replace, $replace_string);
}
$new_contents = preg_replace($search, $replace, $contents);
write_file($file, $new_contents);
}
Maybe it requires some slight performance improvements. But this is my baseline idea.
create the keys with empty values
$config['base_url'] = '';
then set them inside any of your controllers.
This works best if you store the values in the db, and initialize them in MY_Controller.
$this->config->set_item('base_url', 'value');
It is possible. I can't find the code , but once i have written something like that. Whole idea was based on tokenizing template file and substitute values in an array, preserving key order, line numbers and comments from the template.
[+] Found it. It's purpose was to fill values from template that looked like this (it was much bigger of course):
<?php
$_CFG = array(
// DB section
'db_host' => 'localhost',
'db_user' => 'root',
'db_pass' => '',
'db_name' => 'test',
// Site specific
'lang' => array('pl','en'),
'admin' => 'admin#example.com',
);
And the code that was doing all the magic:
$tokens = token_get_all(file_get_contents('tpl/config.php'));
$level = -1;
$buffer = '';
$last_key = 0;
$iteration = 0;
foreach($tokens as $t){
if($t === ')'){
$iteration = 0;
$last_key = 0;
$level--;
}
if(is_array($t)){
if($t[0] == T_ARRAY && strtolower($t[1]) === 'array')
$level++;
if($t[0] == T_CONSTANT_ENCAPSED_STRING){
if($last_key){
if($level){
if(isset($new_config[$last_key][$iteration])){
$buffer .= var_export($new_config[$last_key][$iteration], TRUE);
}
else
$buffer .= 'null';
$iteration++;
}
else{
if(isset($new_config[$last_key]))
$buffer .= var_export($new_config[$last_key], TRUE);
else
$buffer .= 'null';
$last_key = 0;
}
}
else{
$buffer .= $t[1];
$last_key = trim($t[1],"'");
}
}
else
$buffer .= $t[1];
}
else
$buffer .= $t;
}
file_put_contents('config.php',$buffer);

Categories