PHP atomic write function

Motivation:

An atomic write function for those who appreciate the convenience of file_put_contents(), but need an atomic operation.  Please leave a comment if you have a more convenient and/or efficient solution.

Update (5/31/11):

Now using flock, as recommended by Petr and Hayden in their comments below, to avoid race condition. Thanks for the help!

Source code:


function atomic_put_contents($filename, $data)
{
    // Copied largely from http://php.net/manual/en/function.flock.php
    $fp = fopen($filename, "w+");
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, $data);
        flock($fp, LOCK_UN);
    }
    fclose($fp);
}

Example usage:


$content = 'some content';

atomic_put_contents('path/file.ext', $content);

//creates file called path/file.ext containing 'some content'

PHP class to manage read-only vars and arrays

Source code:


class Constants
{
    private $var_cache;

    public function set($key, $val)
    {
        if(isset($this->var_cache[$key]))
        {
            throw(new Exception("Constants->get() error: var $key has already been defined"));
        }
        else
        {
            $this->var_cache[$key] = $val;
        }
    }

    public function get($key)
    {
        return $this->var_cache[$key];
    }
}

Example usage:

$constants = new Constants();

$constants->set('base_url', 'www.domain.com/path');

...

$img_src_url = $constants->get('base_url').'/img/file.jpg';

echo "<img src='$img_src_url' />";