GITLAB

Snippets

Sign in
  • Sign in

file_put_contents_with_version.php
Add new snippet


#77 by 72f60816e60779e1cff35b00d383cb94?s=40&d=identicon doekia
← discover snippets
file_put_contents_with_version.php Buy Me a Coffee at ko-fi.com
raw
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
<?php
/**
 * Write to a file (save) preserving backup of its prior content if any
 *
 * @copyright (c)2017 doekia Enter-Solutions
 * @licence GPL
 *
 * @param string $file the real file name
 * @param string $data the content
 * @param int $flag (Optional)
 * @param mixed $context (Optional)
 * @param string $suffix (Optional) suffix sprintf format - default '.%d'
 * @param int $max (Optional) maximum number of version to preserve - default 9
 * @return bool
 */
 
function file_put_contents_with_version($file, $data, $flag = 0, $context = null, $suffix = '.%d', $max = 9)
{
	for($i = $max; $i; $i--) {
		file_exists($file.sprintf($suffix, $i-1)) && @rename($file.sprintf($suffix, $i-1),$file.sprintf($suffix, $i));
	}
	file_exists($file) && @rename($file,$file.sprintf($suffix, 1));
	if (!is_null($context)) {
		return file_put_contents($file, $data, $flag, $context);
	}
	else {
		return file_put_contents($file, $data, $flag);
	}
}