-
-
Save helgi/848371 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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