Reputation: 300
Good day everyone! I'm relatively new to PHP, but I'm learning fast. Whenever I'm learning a new language I like to take on a complicated, hands-on project that'll hopefully get me well-rounded with the language. As such, I am developing a CMS-like system.
With that said, I've gotten to a point where I'm a little stumped. I've made a form where the user can input their database information. My system goes through, validates the information, and once it's accepted I'd like to store it into a config file. I'd like to set this up similar to Wordpress whereas they have a config file template, copy it to a new name, and edit the values, all-the-while maintaining all white-space and comments. I've skimmed through the Wordpress source files to determine how they've accomplished this and I'm pretty sure they open the file, use regex to find the variable they want to change, then simply overwrite the entire line. So my dilemma is this, I wasn't able to trace everything to figure out exactly how they did this, so even though I know what I need to do I'm not entirely sure how. I've done a ton of research and have not yet found the information I need.
Secondarily, I was hoping you could assist me in determining if this is the best method of accomplishing this. If you know any better methods of storing information into a file, based on a template file, then I'd greatly appreciate your input.
Lastly, looking through other questions of this sort on StackOverflow, many of them say to use an ini file. Though, the answers on those questions don't seem to explain very well how I'd go about doing so. As well, I'd prefer to use a php file, but an ini file isn't completely out of the question if it proves easier, faster, or more reliable.
Thank you very much for your time!
Upvotes: 0
Views: 624
Reputation: 522382
Ultimately you just want to serialize some information into a file and be able to unserialize it again. For this purpose, instead of thinking in "templates", think in terms of serialization of information into a file. PHP's serialize
will do, but is hardly human readable or editable, so just choose a friendlier format instead. Both YAML and JSON are pretty nice for this purpose. E.g.:
$userInput = ['foo' => 'bar', 'baz' => 42];
file_put_contents('config.json', json_encode($userInput, JSON_PRETTY_PRINT));
$configuration = json_decode(file_get_contents('config.json'), true);
INI is also a very simple human editable file format, and PHP can read INI files, but has no function out of the box to also write them.
Upvotes: 1