Skip to content

Instantly share code, notes, and snippets.

@helgi
Created February 28, 2011 23:46
Show Gist options
  • Save helgi/848296 to your computer and use it in GitHub Desktop.
Save helgi/848296 to your computer and use it in GitHub Desktop.
A small function was experimenting with for the PEAR REST cache saving. It was open to link attacks (soft/hard links), attempting to take care of the time-of-check-time-of-use (TOCTOU) race condition as well as being able to create and/or update a cache f
<?php
function saveCacheFile($file, $contents)
{
$serialized = serialize($contents);
$len = strlen($serialized);
$cachefile_fp = @fopen($file, 'xb'); // x is the O_CREAT|O_EXCL mode
if ($cachefile_fp !== false) { // create file
if (fwrite($cachefile_fp, $serialized, $len) < $len) {
return PEAR::raiseError("Could not write $file.");
}
fclose($cachefile_fp);
} else { // update file
$cachefile_lstat = lstat($file);
$cachefile_fp = @fopen($file, 'wb');
if (!$cachefile_fp) {
return PEAR::raiseError("Could not open $file for writing.");
}
$cachefile_fstat = fstat($cachefile_fp);
if (
$cachefile_lstat['mode'] == $cachefile_fstat['mode'] &&
$cachefile_lstat['ino'] == $cachefile_fstat['ino'] &&
$cachefile_lstat['dev'] == $cachefile_fstat['dev']
) {
if (fwrite($cachefile_fp, $serialized, $len) < $len) {
return PEAR::raiseError("Could not write $file.");
}
fclose($cachefile_fp);
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment