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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.