Skip to content

Instantly share code, notes, and snippets.

@helgi
Forked from scottmac/gist:848358
Created Mar 1, 2011
Embed
What would you like to do?
<?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