Jump to content

change value in a configuration file


jason213123

Recommended Posts

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.