Re: best way to save program prefs to a file?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



In larger applications, I prefer to serialize the array because it allows you to store the data in _any_ variable, not just the pre-named variable. For example, if your page is already using a variable named $user_settings, you would run into problems with your solution. My solution allows you to name the data however you want, however many times you want.

Of course, this is usually not necessary for a smaller application where you wouldn't run into such a problem.



Sincerely,

A.J. Brown
BitNotion Technologies
aj@xxxxxxxxxxxxx

----- Original Message ----- From: "Edward Vermillion" <evermillion@xxxxxxxxxxxx>
To: "A.J. Brown" <aj@xxxxxxxxxxxxx>
Cc: <php-general@xxxxxxxxxxxxx>
Sent: Tuesday, September 27, 2005 10:48 AM
Subject: Re:  best way to save program prefs to a file?


A.J. Brown wrote:
Are you wanting the preferences to be real-time changeable? For example, user preferences that can be modified then saved? If so, just store them in an array, then serialize the array and save it to a file. Read the file at every page load.

[code]

//save the settings
$user_settings['setting1'] = 'foo';
$user_settings['setting2'] = 'bar';

$fh = fopen('user_settings.dat');
$serialized = serialize($user_settings);
fwrite ($fh, $serialized, strlen($serialized));
fclose($fh);

//reload the settings
$user_settings = unserialize(file_get_contents('user_settings.dat'));


[/code]


Hope this helps.


I may be showing my ignorance here, but why bother to serialize the array? Why not just write it out to a php file, then all you have to do is include the file when you need it and it's ready to go?

<psudocode alert>

$setingsFile = "<?php\n\n";
foreach($userSettings as $key => $val)
{
    $settingsFile .= "$userSettings[$key] = $val\n";
}
$settingsFile .= "\n?>";

$fh = fopen('/path/to/settingsFile.php', 'w');
fwrite($fh, $settingsFile); // with error handling of course...
fclose($fh);

</psudocode>

Then in your script, include '/path/to/settingsFile.php'; and you're ready to use $userSettings and any changes get written back to the file.



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux