0

I have a PHP configuration file which stores settings like:

  define("SETTING_1", "");
  define("SETTING_2", "");
  define("SETTING_3", "");

By default the settings are empty, but then I have an installer file install.php which basically prompts the user for the settings. What is the best way to open the settings file, find the define for each setting and insert the value? Finally, need to save the settings file to disk.

I want to ovoid using regular expressions or simple string search. I came across token_get_all(), does it makes sense to use it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Justin
  • 42,716
  • 77
  • 201
  • 296

3 Answers3

3

token_get_all() isn't really going to help you, since it's just going to give you all of the parse token from the string. You'll spend more time writing a state machine or parser for the result of token_get_all() than you would with the other methods you listed.

The easiest way to achieve this is to use some sort of known, unique placeholder, like this:

define("SETTING_1", "{{SETTING_1}}");
define("SETTING_2", "{{SETTING_2}}");
define("SETTING_3", "{{SETTING_3}}");

Then, you open the file, and replace all of those placeholders with their actual values using str_replace():

$file = file_get_contents( "config.php");
$config = str_replace( 
    array( '{{SETTING_1}}', '{{SETTING_2}}', '{{SETTING_3}}'),
    array( $setting1, $setting2, $setting3),
    $file
);
file_put_contents( 'config.php', $config);

That's all it takes.

nickb
  • 59,313
  • 13
  • 108
  • 143
0

Is the define() way definite?

If you really NEED to have it in PHP format, use var_export() and include, which is on the other hand totally insecure... or use INI files, i.e. create ini file, write values in PHP

Community
  • 1
  • 1
Miro Hudak
  • 2,155
  • 2
  • 21
  • 29
  • Really? Why is something like http://pastie.org/4368244 more insecure than using .ini files? Thanks. – Justin Aug 01 '12 at 00:07
  • @Justin because as I see it, you have two options: 1) parse it by hand, 2) include it directly ... option 2 is dangerous, when someone modifies your configuration file by hand and you interpret it each time, your application is executed. that's why i would never allow script to modify a file, which is directly included... and of course, option 1 is ineffective as there are better ways to store configuration... – Miro Hudak Aug 01 '12 at 00:12
0

Don't use Constants for user settings. It is a bad idea. Create an array and store in a file with var_export with second parameter 'true'. It is readable and can be regenerated by using array functions.

sriansri
  • 11
  • 1