Coding with Jesse

Saving data to a file with PHP

February 24th, 2008

Lately, I've been skipping using MySQL in situations where I just want to store a few variables, like configuration options, and don't necessarily want the hassle of setting up a database.

You can easily store data to a file using serialize and unserialize to turn a PHP object into a string, and then read and write the string in a file.

Here are a few functions that do just that:

function get_data($filename) {
    // create file if it doesn't exist
    if (!file_exists($filename)) {
        touch($filename);
    }

    return unserialize(file_get_contents($filename));
}

function get_option($filename, $key) {
    $data = get_data($filename);
    return $data[$key];
}

function set_option($filename, $key, $value) {
    $data = get_data($filename);
    $data[$key] = $value;

    // write to disk
    $fp = fopen($filename, 'w');
    fwrite($fp, serialize($data));
    fclose($fp);
}

// probably should put somewhere off the web root
$config = '../config.dat';

set_option($config, 'width', 1024);
echo get_option($config, 'width'); // will echo 1024

So there you have it. Feel free to use or modify this code as much as you like. If anyone has an idea for rewriting it to be cleaner, please share in the comments.


Interested in web development? Subscribe to my newsletter!

Comments

1 . Ed Eliot at 2008-02-24T23:03:06.000Z

Ed Eliot

It might be an idea to cache reading of options and buffer writing. That way you won't potentially hit the file multiple times on a single request.

I'd suggest wrapping the functions in a class to make this a bit easier to achieve.

2 . Harmen Janssen at 2008-02-24T23:53:33.000Z

Harmen Janssen

Make sure to familiarize yourself with the __sleep and __wakeup methods when serializing objects (http://php.net/__sleep)!

Also, for an object oriented solution, you might be interested in the File and Cache classes I've written (http://whatphp.net/class.php?package=util/FileSystem/File/1.0&class=File&view=api and http://whatphp.net/class.php?class=Cache&package=util/Cache/1.0)

3 . Handan Daily at 2008-03-26T03:16:39.000Z

Handan Daily

jquery is great!

4 . Handan Daily at 2008-03-26T03:17:21.000Z

Handan Daily

your article chinese version
http://www.ibm.com/developerworks/cn/xml/x-ajaxjquery.html

呵呵!

5 . Someone at 2008-05-08T01:29:00.000Z

Someone

Pretty good idea, I'll have plenty of uses for it.

6 . Stephen Mann at 2010-05-28T13:57:26.000Z

Stephen Mann

Thanks - this is exactly what I need.