Fastest way to store easily editable config data in PHP?

PHPServer Side ProgrammingProgramming

Serialize is better in comparison to JSON to store PHP variables.

The var_export can be used to save config file, and 'include' can be used to load the config file information.

This is an easy way to save config data programmatically and easier to read/write. Below is a sample code for the same −

config.php

return array(
   'var_1'=> 'value_1',
   'var_2'=> 'value_2',
);

test.php

$config = include 'config.php';
$config['var_2']= 'value_3';
file_put_contents('config.php', '<?php return ' . var_export($config, true) . ';');

Instead of the above test.php, the below code can also be used −

$config = include 'config.php';
$config['var_2']= 'value_3';
file_put_contents('config.php', '$config = ' . var_export($config));

The updated config.php contains the following code −

return array(
   'var_1'=> 'value_1',
   'var_2'=> 'value_3',
);
raja
Published on 06-Apr-2020 12:16:51
Advertisements