note 71169 deleted from function.file-exists by tularis
| From: | tularis@php.net | Date: | Wed, 15 Nov 2006 09:01:41 +0000 |
| Subject: | note 71169 deleted from function.file-exists by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-119740@lists.php.net to get a copy of this message | ||
Note Submitter: Tomek Perlak [tomekperlak at tlen pl]
----
If you want to make sure you don't overwrite an exising file (or to rename the existing file to
a valid, yet similar name), the following function, next_filename(), can come in handy:
<?
function next_filename($fn, $i = 1)
{
$i--;
while (file_exists($next_fn = str_replace_last($fn, ".", "." . (++$i) .
".")));
return $next_fn;
}
?>
(It depends on the str_replace_last() function, defined as follows):
<?
function str_replace_last($where, $what, $with_what)
{
$tmp_pos = strrpos($where, $what);
if ($tmp_pos !== FALSE)
{
$where = substr($where, 0, $tmp_pos) . $with_what . substr($where, $tmp_pos +
strlen($what));
}
return $where;
}
?>
You pass two parameters to this function - the file name (assuming it's the file you'd
like to keep or backup) - and a starting index, by default 1.
If your file name is, say, "my_file.txt", and there are no 'backup copies' in
its folder, the function will return "my_file.1.txt".
If, in turn, your folder has the following files in it:
my_file.txt
my_file.1.txt
my_file.a.txt,
then the function will return "my_file.2.txt". And so on.