3

I have this php setup of writing a config file directly and i would like to update the variable in the file instead of writing the whole file. Can anyone point me in the right direction?

  $allowedExts = array(".jpg", ".jpeg", ".gif", ".png");
  $extension = strrchr ($_FILES["logoFile"]['name'], '.');

  if (($_FILES["logoFile"]["size"] < 2000000)
  && in_array($extension, $allowedExts))
  {
if ($_FILES["logoFile"]["error"] > 0)
{
    echo "Return Code: " . $_FILES["logoFile"]["error"] . "<br />";
}
else
{

move_uploaded_file($_FILES["logoFile"]["tmp_name"],"../../upload/logo".$extension);



$path= "./upload/logo".$extension;

//update logo settings variable

$data = file_get_contents('../settings/settings.php'); // grab data
$data = str_replace("/'LOGO_IMAGE_PATH', '[^']+'/", "'LOGO_IMAGE_PATH', '$path'", $data); // replace that section
file_put_contents('../settings/settings.php', $data); // save data


}
}
else
{
    echo "Invalid file";
}

And the rest of the variables are from the saveSettings.

case "saveSettings":

        //Logo settings
        $showLogo=$_REQUEST["showLogoOption"];
        $roundOption=$_REQUEST["roundOption"];
        $siteTitle=$_REQUEST["siteTitle"];
        $requireJobTypes=$_REQUEST["requireJobTypes"];
        $enableJobTypes=$_REQUEST["useJobTypes"];
        $enableMileage=$_REQUEST["enableMileage"];
        $allowViewingPayrolls=$_REQUEST["allowViewingPayrolls"];
        $trackIP=$_REQUEST["trackIP"];
        $enableMobile=$_REQUEST["enableMobile"];
        $config="<?php 
           define('USE_LOGO_IMAGE', $showLogo);
           define('ROUND_TO_QUARTERS', $roundOption);
           define('SITE_TITLE', '$siteTitle');
           define('ENABLE_JOB_TYPES', $enableJobTypes);
           define('REQUIRE_JOB_TYPES', $requireJobTypes);
           define('ENABLE_MILEAGE', $enableMileage);
           define('ALLOW_VIEW_PAYROLLS', $allowViewingPayrolls);
           define('TRACK_IP', $trackIP);
           define('MOBILE_VERSION_ENABLED', $enableMobile);
        ?>";
        $fp = fopen("../settings/settings.php", "w");
        fwrite($fp, $config);
        fclose($fp);
        break;    

Thank you.

2
  • This might be a possible duplicate of stackoverflow.com/questions/14351407/… Commented Mar 1, 2013 at 7:04
  • Is the file already made, and you just want to update it once during setup? Commented Mar 1, 2013 at 11:05

2 Answers 2

1

This is the function that will update settings for you, it will do it so your settings.php file is only modified once during the setup process so it won't needlessly open the file for every setting. It will save them all in one swoop.

function save_settings($settings) // function to update settings to file
{
    $data = file('../settings/settings.php', FILE_SKIP_EMPTY_LINES); // grab current settings file

    foreach ($data as $key => $line) // loop through lines in file
    {
        foreach ($settings as $name => $value) // loop through settings that are being modified
        {
            if (strcasecmp('true', $value) && strcasecmp('false', $value)
            && '0' !== $value && '1' !== $value)
            {
                $value = "'" . htmlspecialchars($value, ENT_QUOTES) . "'"; // quote non-boolean, also escape quotes
            }

            if (FALSE !== strpos($line, $name)) // if exists update it
            {
                $data[$key] = "define('" . $name . "', " . $value . ");\n"; 
            }
        }
    }
    file_put_contents('../settings/settings.php', implode('', $data)); // save it all
}

Put this line at the beginning of our setup process

// run this line BEFORE you begin to set values in settings.php to initialize the settings array
$settings = array();

You then modify settings like so:

// update settings easily by doing the below anywhere you like
// as long as it is after the above line and before you run save_settings()
$settings['LOGO_IMAGE_PATH']        = $path;
$settings['USE_LOGO_IMAGE']         = $_POST['showLogoOption'];
$settings['ROUND_TO_QUARTERS']      = $_POST['roundOption'];
$settings['SITE_TITLE']             = $_POST['siteTitle'];
$settings['ENABLE_JOB_TYPES']       = $_POST['requireJobTypes'];
$settings['REQUIRE_JOB_TYPES']      = $_POST['useJobTypes'];
$settings['ENABLE_MILEAGE']         = $_POST['enableMileage'];
$settings['ALLOW_VIEW_PAYROLLS']    = $_POST['allowViewingPayrolls'];
$settings['TRACK_IP']               = $_POST['trackIP'];
$settings['MOBILE_VERSION_ENABLED'] = $_POST['enableMobile'];

Then when you are all done you finalize the settings file by saving it with the updated settings:

// run this line at the end to save ALL settings AFTER you are done setting their values
save_settings($settings);
Sign up to request clarification or add additional context in comments.

4 Comments

It would be more slower than regular method.
@dexter4000 after I thought about it it would be impossible to sanitize the vars against bad PHP code, so you need to just protect the form itself. I can't paste on pastebin as it would not benefit this site as the code will not show up in search engines and it makes it inconvenient for other visitors to use it as well. Anyway, I posted it, and commented it as much as I could. Btw you should use $_POST instead of $_REQUEST
@dexter4000 are you using the words true and false for your boolean? If so see update. Btw please delete your above comments, so this post doesn't get cluttered with out discussion =o) I've deleted mine.
@crypticツ yes the boolean are true and false. Thanks a lot again.
0

you can do something like this.

// Pass the array to update

function update_config($myConfig) {
  $myConfig = json_encode($myConfig);
  $fp = fopen('my_config.ini', 'a');
  fwrite($fp, $myConfig);
  return 'success';
}

// update config when you need

$myConfig = array();
$myConfig['section_1'] = "a";
$myConfig['section_2'] = "b";
$myConfig['section_3'] = "c";
echo update_config($myConfig)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.