Welcome Guest, Not a member yet? Register   Sign In
How can I write file without overwrite
#3

(06-17-2019, 04:36 PM)mladoux Wrote: If you're just appending, you need to check if the file exists first, else you'll break it every time. If you want to overwrite it, I suggest unlinking the file. I wrote a couple of examples below that should work, depending on your use-case. That said, I don't recommend anything that potentially writes user inputs directly into a php file.


PHP Code:
<?php

// Overwrite file completely
function createNewSettingsFile()
{
  $file FCPATH '/settings.php';
  $submit $this->input->post('submit');
  if (isset($submit)) {
    $html '<?php'.PHP_EOL.PHP_EOL;
    foreach ($this->input->post('settings') as $key => $value) {
      $html .= '$settings['".$key."'] = "' $value '";' PHP_EOL;
    }

    // Make sure the file doesn't exist to prevent just appending and thus
    // breaking the output of this function.
    if (file_exists($file)) {
      unlink($file);
    }

    file_put_contents($file$html);
  }
}

// Add to existing file, if it exists
function addNewSettings()
{
  $file FCPATH '/settings.php';
  $submit $this->input->post($submit);

  if (isset($submit)) {

    // Check if file exists before adding <?php
    $html = (file_exists($html)) ? '' '<?php'.PHP_EOL.PHP_EOL;

    foreach ($this->input->post('settings') as $key => $value) {
      $html .= '$settings['".$key."'] = "' $value '";' PHP_EOL;
    }

    // Write the contents ( added FILE_APPEND to make sure we are adding
    // and definitely not just creating a new file )
    file_put_contents($file$htmlFILE_APPEND);
  }


I use your second method function addNewSettings. 

It's good but when I update any setting for example settings.php has 
PHP Code:
$settings["jumboH1"]="Login h1 test";
$settings["jumboParag"]="Login paragraph test";
$settings["panel1"]="Panel 1";
$settings["panel2"]="Panel 2";
$settings["panel3"]="Panel 3"

Then I submit form for update some settings. 

PHP Code:
$settings["jumboH1"]="Login h1 test";
$settings["jumboParag"]="Login paragraph test";
$settings["panel1"]="Panel 1";
$settings["panel2"]="Panel 2";
$settings["panel3"]="Panel 3";
$settings["jumboH1"]="Login h1 testNEW";
$settings["jumboParag"]="Login paragraph testNEW";
$settings["panel1"]="Panel 1NEW";
$settings["panel2"]="Panel 2NEW";
$settings["panel3"]="Panel 3NEW"

It's not updating existing settings, add new lines after the already existing
Reply


Messages In This Thread
How can I write file without overwrite - by bomi - 06-17-2019, 01:41 PM
RE: How can I write file without overwrite - by bomi - 06-18-2019, 02:29 PM



Theme © iAndrew 2016 - Forum software by © MyBB