Kedor
Kedor

Reputation: 1498

Change variable value saved to file.php

I got a file called variables.php

<?php
   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = 'password';
   $dbname = 'database_name';
?>

I know i can access these variables using include and then using them as i use any other variable but i wish to know, how can i change these variables values. And i don't mean $dbhost = "other_value";. I mean how can i save the new value to that file. I was reading about php and file opening/writing/closing, but i cant find a way, how to place myself and replace the value i want.

The only info i have, is the name of the variable, and the value saved to it right now. I am not sure in what line i can find that variable - if that changes anything. So the question is, how to change (using php) variable dbhost to anything else, that user will put in form. (form part isn't a problem, lets say user value was saved to $_POST['uservalue'])

Thanks in advance.

Upvotes: 3

Views: 13238

Answers (5)

T.Todua
T.Todua

Reputation: 56555

for example, you have settings.php, and there is already set $your_variable='hi Mike'; and you want to change it to 'hi Joshua':

<?php
$file='settings.php'; 

//read file
$content=file_get_contents($file);

// here goes your update
$content = preg_replace('/\$your_variable=\"(.*?)\";/', '$your_variable="hi Joshua";', $content);

//write file
file_put_contents($file);
?>

p.s.1) BE CAREFUL ! ! ! I dont know why you are doing that method. You are doing very dangerous thing! I havent seen anything coded like that. You can easily be hacked, because someone might write a variable in PHP file, that will execute like a function and GETS YOUR WHOLE SITE.

p.s.2) use not .php extension, but something else (i.e. '.txt'), and FILTER values before saving!

p.s.3) Use MYSQL database, instead of writing to file. Yes, that needs to Spend 30 minutes more, but you get much safety.

Upvotes: 4

DaveRandom
DaveRandom

Reputation: 88707

NOTE Added 04/2013:

This is a bad idea. You should not be modifying configuration file like this. If you you have configuration that can be administered by the user, you should be storing it in a database or, worst case scenario, in a generic file format (ini, XML etc). A configuration file that stores the database connection details should never be modified by an application, only manually by the administrator - because it is important that the file is secure and it is an event that should be very rare.

Calling include/require on a file that is dynamically modified is asking for trouble.


Original answer below

function change_config_file_settings ($filePath, $newSettings) {

    // Get a list of the variables in the scope before including the file
    $old = get_defined_vars();

    // Include the config file and get it's values
    include($filePath);

    // Get a list of the variables in the scope after including the file
    $new = get_defined_vars();

    // Find the difference - after this, $fileSettings contains only the variables
    // declared in the file
    $fileSettings = array_diff($new, $old);

    // Update $fileSettings with any new values
    $fileSettings = array_merge($fileSettings, $newSettings);

    // Build the new file as a string
    $newFileStr = "<?php\n\n";
    foreach ($fileSettings as $name => $val) {
        // Using var_export() allows you to set complex values such as arrays and also
        // ensures types will be correct
        $newFileStr .= "\${$name} = " . var_export($val, true) . ";\n";
    }
    // Closing ?> tag intentionally omitted, you can add one if you want

    // Write it back to the file
    file_put_contents($filePath, $newFileStr);

}

// Example usage:
// This will update $dbuser and $dbpass but leave everything else untouched

$newSettings = array(
    'dbuser' => 'someuser',
    'dbpass' => 'newpass',
);
change_config_file_settings('variables.php', $newSettings);

Upvotes: 7

Lit
Lit

Reputation: 1129

I Succeed by this:

$file = 'file.php';
$content = file_get_contents($file);
$replacement = 'replace';
$content = preg_replace('/find/', $replacement, $content);
file_put_contents($file, $content);

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 158003

I can't find any reason to change these values.

The only sane use case I can think of is creation of such a file from the scratch.

So, you can use var_export() to have properly escaped values ready to be written to the file

Upvotes: 2

Yaniro
Yaniro

Reputation: 1587

Perhaps you should consider placing your configuration file in a .ini file which will look like this:

dbhost = "localhost"
dbuser = "root"
dbpass = "password"
dbname = "database_name"

Then you read the file using:

$config = parse_ini_file( "/the/path/to/file.ini" );

Then you access the values like:

connect_to_db( $config[ 'dbhost' ], $config[ 'dbuser' ] );

You can then change the values directly like:

$config[ 'dbhost' ] = 'new host';

Then you write the file like:

$f = fopen( "/the/path/to/file.ini", "w" );
foreach ( $config as $name => $value )
{
    fwrite( $f, "$name = \"$value\"\n" );
}

fclose( $f );

Please note that if the values might contain double quotes, you will need to escape $value in the loop before writing like so:

$value = str_replace( '"', '\"', $value );

Also, please remember to place the .ini file outside of the htdocs directory or any other directory which is accessible through the web as people will be able to download the file and see its content...

Upvotes: 3

Related Questions