Skip to content

Instantly share code, notes, and snippets.

@helgi
Forked from scottmac/gist:848358
Created March 1, 2011 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helgi/848371 to your computer and use it in GitHub Desktop.
Save helgi/848371 to your computer and use it in GitHub Desktop.
<?php
function saveCacheFile($file, $contents)
{
$len = strlen($contents);
$cachefile_fp = @fopen($file, 'xb'); // x is the O_CREAT|O_EXCL mode
if ($cachefile_fp !== false) { // create file
if (fwrite($cachefile_fp, $contents, $len) < $len) {
fclose($cachefile_fp);
return PEAR::raiseError("Could not write $file.");
}
} 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'] &&
$cachefile_fstat['nlink'] === 1
) {
if (fwrite($cachefile_fp, $contents, $len) < $len) {
fclose($cachefile_fp);
return PEAR::raiseError("Could not write $file.");
}
} else {
fclose($cachefile_fp);
$link = function_exists('readlink') ? readlink($file) : $file;
return PEAR::raiseError('SECURITY ERROR: Will not write to ' . $file . ' as it is symlinked to ' . $link . ' - Possible symlink attack');
}
}
fclose($cachefile_fp);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment