1

Possible Duplicate:
writing to a .php file?

So I have a config.php file for a CMS that I created from scratch. This file has the structure shown below:

<?php

date_default_timezone_set( "America/Phoenix" );
define( "DB_HOST_USER", "mysql:host=localhost;dbname=db_cms" );
define( "DB_USERNAME", "username" );
define( "DB_PASSWORD", "password" );
define( "CMS_TITLE", "Sample Title");
define( "USERNAME", "cms_user");
define( "PASSWORD", "cms_password");

?>

My question is that how can I write into this file and save it to the disk using PHP. Help would be greatly appreciated.

Edit: I saw that WordPress uses similar kind of file structure to store user/application configuration as outlined here. I was just wondering if I can change above file (config.php) and store new setting in there. For instance, I want to set USERNAME to blog_user (define( "USERNAME", "blog_user");). Is it possible to just store this change without rewriting the entire file?

1
  • 1
    What do you mean? The PHP file itself is saved to disk already. Are you trying to create an editable config file? Commented May 31, 2012 at 19:51

3 Answers 3

4

I'm not sure why you want to do this, but you can use file_put_contents to write to any file as long as the user PHP is running as has write permissions:

file_put_contents('filename', '<?php

date_default_timezone_set( "America/Phoenix" );
define( "DB_HOST_USER", "mysql:host=localhost;dbname=db_cms" );
define( "DB_USERNAME", "username" );
define( "DB_PASSWORD", "password" );
define( "CMS_TITLE", "Sample Title");
define( "USERNAME", "cms_user");
define( "PASSWORD", "cms_password");

?>
');
Sign up to request clarification or add additional context in comments.

3 Comments

Not quite, I don't want to rewrite the entire file like that. Rather, I was wondering if there was a way to just set one line that was changed.
@GopalAdhikari I see now. In that case I recommend that instead of a bunch of constants you create an array or object for configuration. Then you can serialize it and store it in a file or store it as JSON or YAML or .ini, or one of many other formats.
Yeah, that's what I am trying to do now. I saw in php.net that I could use the serialize and unserialize functions to achieve what I want to do. Thanks for your effort though.
0

Assuming you want to save it to the disk on the server, the following code could be used:

$ourFileName = "testFile.txt";
$temp = file_get_contents($ourFileName);

Do any necessary changes to $temp where new data can be appended, etc and then:

file_put_contents($ourFileName,$temp);

http://php.net/manual/en/function.file-get-contents.php

Comments

0

There are plenty of ways to store configuration data. Try this Stack Overflow: Fastest way to store easily editable config data in PHP?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.