
Reading and Writing Configuration Files
Question:
How can one modify a string in a configuration file using data from a PHP form ($_POST variable)?
Answer:
Consider using a structured file format like CSV, Ini, XML, JSON, or YAML. Utilize dedicated APIs to read and write these formats.
Alternative Approaches:
-
Array Storage: Store the configuration in an array and use serialize/unserialize or var_export/include to persist it.
-
Custom Class: Implement a class that encapsulates read/write operations for a custom configuration format.
Example:
A basic PHP class for managing configuration files:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class MyConfig
{
public static function read( $filename )
{
$config = include $filename ;
return $config ;
}
public static function write( $filename , array $config )
{
$config = var_export( $config , true);
file_put_contents ( $filename , "<?php return $config ;" );
}
}
|
Copy after login
Usage:
1 2 3 4 5 6 7 8 9 10 | MyConfig::write( 'conf1.txt' , [ 'setting_1' => 'foo' ]);
$config = MyConfig::read( 'conf1.txt' );
$config [ 'setting_1' ] = 'bar' ;
$config [ 'setting_2' ] = 'baz' ;
MyConfig::write( 'conf1.txt' , $config );
|
Copy after login
The above is the detailed content of How to Modify a Configuration File String Using PHP Form Data?. For more information, please follow other related articles on the PHP Chinese website!