BigToach.com

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
?>

Added on Feb 21st at 4 pm by Scott - 0 Comments
Updated on Feb 21st at 4 pm.


0 Responses to find_filename

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: