Skip to content

Instantly share code, notes, and snippets.

@scottmac
Forked from helgi/gist:848296
Created March 1, 2011 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save scottmac/848358 to your computer and use it in GitHub Desktop.
Save scottmac/848358 to your computer and use it in GitHub Desktop.
<?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);
} else {
fclose($cachefile_fp);
return PEAR::raiseError('SECURITY ERROR: Will not write to ' . $file . ' as it is symlinked to ' . readlink($file) . ' - Possible symlink attack');
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment