jason213123 Posted February 13, 2012 Share Posted February 13, 2012 hi, i have a configuration file with this content for example: test = "100"; teste2 = "300"; now need change the test from 100 to 300, i just want use something like this: function ( "test" , 300 ); how can i do that? thanks for help Quote Link to comment https://forums.phpfreaks.com/topic/257088-change-value-in-a-configuration-file/ Share on other sites More sharing options...
PaulRyan Posted February 14, 2012 Share Posted February 14, 2012 I assume by the format you have in the example given, you are using a plain text file. This is a function I've come up with: <?PHP function updateConfig($setting, $newValue, $filePath ,$backup=FALSE) { $config = file($filePath); $fileInfo = pathinfo($filePath); if($backup == TRUE) { $backupFile = $fileInfo['filename'].'-'.$_SERVER['REQUEST_TIME'].'.'.$fileInfo['extension']; if(file_put_contents($backupFile,file_get_contents($filePath))) { return true; } else { return false; } } foreach($config AS $line => $value) { if(strpos($value,$setting.' ') !== FALSE) { //### Find the setting value preg_match('#["](.*)["]#',$value,$matches); //### Use first match, as we only want to change what is inside the double quotes $config[$line] = preg_replace('#'.$matches[0].'#', '"'.$newValue.'"', $value); //### Implode the contents to write it too the file $config = implode("",$config); break; } } if(file_put_contents($filePath,$config)) { return true; } else { return false; } } if(updateConfig('test', '500', 'test.txt', TRUE)) { echo 'Config Updated!'; } else { echo 'Config Not Updated!'; } ?> I got this working, so try it out for yourself. Regards, PaulRyan. Quote Link to comment https://forums.phpfreaks.com/topic/257088-change-value-in-a-configuration-file/#findComment-1317937 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.