Rewrite and close array of a file

Asked

Viewed 896 times

10

How do I open a configuration file, rewrite the value of an array, and close and save the file? Example: config.php

return Array {
    'DB_TYPE' => 'mysql',
    'DB_USER' => 'root'
}

config.php (After function execution):

return Array {
    'DB_TYPE' => 'pgsql',
    'DB_USER' => 'root'
}

Note that DB_USER was not affected. Could use fopen(), fwrite() and fclose() to do this, but would end up losing the other arrays.

The fuelphp framework has this function (save()): http://fuelphp.com/docs/classes/config.html

I’m not using any framework .

  • Do you want to persist the data? You will have to use a database or save the settings to a file. It is possible to store the data using Session (http://php.net/manual/en/features.sessions.php), but when you close the browser the session is destroyed and the value of the array returns to the initial value.

  • what I understood is that it has a command that when running it wants to modify the bd configuration file and save the file with a different attribute.

  • That’s right @Skywalker

  • I don’t understand ... explain better this scheme of reading/recording the file that Skywalker commented.

  • Without time to come up with an answer, I will try to explain what I understood, it has a configuration file, that inside ta saved this code return array (
 'DB_TYPE' => 'mysql'); at a certain point he wants to modify this file and change where it is mysql for pgsql );

  • This return array (
 'DB_TYPE' => 'mysql'
); it seems to me that the of some framework. Tell me Voce can not manually edit the configuration file?

  • This question is being discussed here: http://meta.pt.stackoverflow.com/q/4295/3635

  • Good evening, I still don’t understand if you’re using fuelphp or not, could you be clearer? You want to change the values of these configuration files, and a system that you are creating? How does this system work? What is your exact goal?

  • Yes, it is a Class that I am developing; its goal is to obtain, set and save the configuration file. I’m not using Fuelphp, I just gave an example of which framework has a similar function

  • Got an answer? the config file has the tag <?php?

  • 1

    You invented this keyed array structure ? Because array in PHP exists in two ways: return array('chave'=>'valor') and return ['chave'=>'valor'] (version 4.5 or >)

Show 6 more comments

6 answers

4


I will divide the answer into three parts: reading the file, modification and writing.

Reading

The function require usually includes a file to be executed - but if its return is assigned to a variable, it gets the content returned by that file.

Filing cabinet array.php:

return array(
    'DB_TYPE' => 'mysql',
    'DB_USER' => 'root'
);

Filing cabinet index.php:

$array = require('array.php');

Modification

We modify the desired key, as we would normally do:

$array['DB_TYPE'] = 'pgsql';

Writing

Here we write the configuration file again using the function var_export, that exports a variable in a way that can be understood by PHP. In addition, we have entered the opening tag and other characters needed so that there is no syntax error when reading the file again.

file_put_contents(
    'array.php',
    '<?php' . PHP_EOL . PHP_EOL . 'return ' . var_export($array, true) . ';'
);

So, at the end of the day, the script would look like this:

<?php

$array = require('array.php');
$array['DB_TYPE'] = 'pgsql';

file_put_contents(
    'array.php',
    '<?php' . PHP_EOL . PHP_EOL . 'return ' . var_export($array, true) . ';'
);

  • +1 I gave the answer, but had not noticed that we had done the same thing.

2

One of the ways to do this is to:

Setting the settings. Where $current_db_type is the line you want to change in the file. And $new_db_type is the change you want to make.

$current_db_type = "'DB_TYPE' => 'mysql'"; 
$new_db_type = "'DB_TYPE' => 'pgsql'";

Then, instantiating the SplFileObject to open the file as read

$file = new SplFileObject('config.php', 'r');

Then starting a variable with the name of output to assemble the configuration file line by line, including the altered line.

$output = '';

Then we will go through the file lines and if we find the match amid $line and $current_db_type - which is the line we want to change - then we will change to the values of $new_db_type.

foreach ($file as $line) {
  if (trim($file) == $current_db_type) {
      $line = $new_db_type.PHP_EOL;
  }
  $output .= $line;
}

Finally we save the changes to the file

$file = new SplFileObject('config.php','w+');
$file->fwrite($output);

Notes:

  1. I used Trim to remove the spaces, as they do the match fail.
  2. I used PHP_EOL to be able to break the line. EOL means End Of Line.

References: Splfileobject, Foreach, Trim, Predefined Constants

0

This function below searches line by line to string that you want and gives a replace.

You need a form to do the POST also ?

INDEX.php

<?php

    $arquivo = fopen('config.php','r+');
    $string = '';

    if ($arquivo) {
        while(true) {
            $linha = fgets($arquivo);
            if ($linha==null) break;

            # Busca na linha atual o que vai ser alterado
            if(preg_match("/mysql/", $linha)) {
                $string .= str_replace("mysql", "pgsql", $linha);
            }else{
                # Coloca tudo em uma nova string
                $string.= $linha;
            }
        }

        # Move o ponteiro para o início do arquivo
        rewind($arquivo);

        # Apaga tudo o que tem no arquivo
        ftruncate($arquivo, 0);

        # Reescreve o arquivo
        if (!fwrite($arquivo, $string)) 
            die('Não foi possível atualizar o arquivo.');

        echo 'Arquivo atualizado com sucesso';
        fclose($arquivo);
    }

?>

CONFIG.php

<?php

    return [
        'DB_TYPE' => 'mysql',
        'DB_USER' => 'root'
    ]

?>

0

Speak friend, it is possible yes! Using only a few functions this is simple.

    public function SetKeywords($Setkeyword, $Setvalue){
        if(gettype($this->words) != 'array'){
            $this->words = array();
        }
        $array = array($Setkeyword => $Setvalue);
        $this->words = array_merge($array,$this->words);
    }

    public function ReplaceKeywords($maskContent) {
        if($this->words){
            if(!$maskContent || strlen($maskContent) == 0)
                return $maskContent;

            foreach($this->words as $keyword=>$value)
            {
                $keyword = '{'.$keyword.'}';
                $maskContent = str_replace($keyword, $value, $maskContent);
            }
            return $maskContent;
        }
        else
        { 
        return false; 
        }
    }

    public function GetReplaceKeywordCount($maskContent){
            if(!$maskContent || strlen($maskContent) == 0)
                return $maskContent;
            $count = array();
            foreach($this->words as $keyword=>$value){
                $searchWord = '{'.$keyword.'}';
                $wordCount = substr_count($maskContent, $searchWord);
                if($wordCount > 0)
                    $count[$keyword] = $wordCount;
            }
            return $count;
    }
}

# instancia da classe
$string = new string;



# definindo o valor para cada variavel dentro
# neste exemplo a variavel {DB_TYPE} dentro do arquivo será
# alterada para MySQL
$string->SetKeywords('DB_TYPE', 'MySQL');
$string->SetKeywords('DB_USER', 'root');


# aqui você pode abrir o arquivo
# p.x:
#
# file_get_contents(filename)

$arrayConfig = "$configs = [
    'DB_TYPE' => '{DB_TYPE}',
    'DB_USER' => '{DB_USER}'
]";



# aqui a class string irá dar replace nas tag pelo valor definido na função SetKeywords
$string = $string->ReplaceKeywords($arrayConfig);

# aqui você poderá salvar o arquivo com fwrite()
echo $string; // return string

In action: http://codepad.org/2C8fP670

This class sets the value for variable, opens the file, takes the content and the class will go through the string, where it finds the variable will change to the value you set.

Show!

In need of a touch, hugs!

0

I’d do it this way.

Suppose I have the following code:

return array(
    'nome' => 'Wallace',
    'idade' => '25 anos'
);

We could take the value of this file and save it in the same script.

For this we will use include, by assigning the return value to the variable. Then we change the value by variable and save the contents of this variable through the function var_export.

Behold:

$configfile = 'configuracao.php';

$config = include $configfile;

$config['nome'] = 'Wayne';

file_put_contents($configfile, '<?php ' . var_export($config, true));

The var_export will export the variable value as a valid PHP code. Note that I used true in the second parameter, so that the var_export does not print, but returns the values. So we can save them in a file.

And the result of the file configuracao.php would be:

return array(
   'nome' => 'Wayne',
   'idade' => '25 anos'
);

-1

Actually I found the question a little confusing, but I’ll start, try the following:

$array=array ('DB_TYPE' => 'mysql', 'PASS'=>'123', 'USER'=>'root');

here changes the value:

$array['DB_TYPE']='pgsql';
echo $array ['DB_TYPE'];
  • Not quite what I wanted to do, read @Skywalker’s comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.