PHP Snippets
find_filename
Information
(PHP Version >= 3)Functions used in this snippet: pathinfo, str_replace, file_exists.
Description
string find_filename( string filename )
Creates a unique filename if one already exists (similar to an operating systems naming schema Ex: file.ext already exists so the new file becomes file-1.ext)
Snippet
<?php
function find_filename($filename)
{
$info = pathinfo($filename);
$info['filename'] = str_replace('.' . $info['extension'], '', $filename);
$i = 1;
while(file_exists($filename))
{
$filename = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . "-$i." . $info['extension'];
$i++;
}
return $filename;
}
?>
Example
find_filename Can be used in the following way:
<?php
<?php
// A file that does not exist
$filename = find_filename('file.txt'); // returns ./file.txt
touch($filename); // create file.txt so it exists now
$filename = find_filename('file.txt'); // returns ./file-1.txt
touch($filename) // create file-1.txt so it exists now
$filename = find_filename('file.txt'); // returns ./file-2.txt
// etc etc
?>
Updated on Feb 21st at 4 pm.
0 Responses to find_filename