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?

Community
  • 1
  • 1
hyde
  • 2,525
  • 4
  • 27
  • 49
  • 1
    What do you mean? The PHP file itself is saved to disk already. Are you trying to create an editable config file? – dpk2442 May 31 '12 at 19:51

3 Answers3

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");

?>
');
Paul
  • 139,544
  • 27
  • 275
  • 264
  • 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. – hyde May 31 '12 at 22:55
  • 1
    @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. – Paul May 31 '12 at 22:57
  • 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. – hyde Jun 03 '12 at 09:16
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

Rohan Durve
  • 340
  • 2
  • 14
0

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

Community
  • 1
  • 1
dpk2442
  • 701
  • 3
  • 8