note 71169 added to function.file-exists

From: Date: Tue, 14 Nov 2006 17:12:19 +0000
Subject: note 71169 added to function.file-exists
Groups: php.notes 
Request: Send a blank email to php-notes+get-119728@lists.php.net to get a copy of this message
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. ---- Server IP: 66.163.161.117 Probable Submitter: 217.30.156.35 ---- Manual Page -- http://www.php.net/manual/en/function.file-exists.php Edit -- https://master.php.net/note/edit/71169 Del: integrated -- https://master.php.net/note/delete/71169/integrated Del: useless -- https://master.php.net/note/delete/71169/useless Del: bad code -- https://master.php.net/note/delete/71169/bad+code Del: spam -- https://master.php.net/note/delete/71169/spam Del: non-english -- https://master.php.net/note/delete/71169/non-english Del: in docs -- https://master.php.net/note/delete/71169/in+docs Del: other reasons-- https://master.php.net/note/delete/71169 Reject -- https://master.php.net/note/reject/71169 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#119728) next »