PHP – avoid overriding past saved data by using a function to get the next available filepath

There are many situations where you need to save data, and there might be an arbitrary number of past data saved. In these cases, you might not want to override the past data files, but simply save your new data alongside it. Since I’ve encountered this situation many times, in order to quickly deal with it, I’ve put together a small and cozy function which returns the next available filename.

function next_available_filepath($filename_pattern, $iterator_start = 0)
{
	// you give it a filepath like C:\test\random_filename_[i].txt
	// and it will try replacing [i] with ascending numbers, and it will give you back the first available filepath
	// useful to avoid overriding files
	
	$filepath = '';
	$i = $iterator_start;
	do
	{
		$filepath = str_replace('[i]', $i, $filename_pattern);
		$i++;
	} while (file_exists($filepath));
	return $filepath;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close