Frank Kluytmans
Frank Kluytmans

Reputation: 543

Append a number to a filename if an image with that name already exists

I wrote some php that checks if a file already exists when a user uploads a new file, and if so appends a string to the filename. What I want is that a number is added to the end of the filename and when another file with the same name is uploaded it tops the number by 1.

So for example: I already have an image uploaded with filename image.png and I upload another one with the same filename. That file should be renamed to image0.png. When I try to upload another image with filename image.png it should be renamed to image1.png and so on.

I'm not sure how to accomplish this within my code. Can anyone help me out? This is the code snippet that checks for duplicates and appends something to the filename.

if(file_exists("/customers/d/8/e/frankkluytmans.nl/httpd.www/testsite/cms/upload/".$_FILES["image"]["name"]))
{
    $filename = explode(".",$_FILES['image']['name']);
    $imageName = $filename[0]."hoi.".$filename[1];
}
else
{
    $imageName = $_FILES['image']['name'];
}

$image = mysql_real_escape_string(htmlspecialchars("/upload/".$imageName));

if (move_uploaded_file($_FILES["image"]["tmp_name"],     "./upload/".$imageName)) {�

mysql_query("INSERT frankkluytmans SET pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error()); 

header("Location: index.php"); 

}

Upvotes: 0

Views: 2055

Answers (2)

Kai Qing
Kai Qing

Reputation: 18833

You could use a recursive function to keep checking the number:

function checkFile($path, $file, $ext, $number)
{
    if(file_exists($path.$file.$number.$ext))
    {
        if($number == "")
            $number = 0;

        $number ++;
        return checkFile($path, $file, $ext, $number);
    }

    return $path.$file.$number.$ext;
}

//run mime type things to get extension. for now lets pretend it is .jpg
// and assume you stripped the extension from the uploaded file...
// also, pass blank to last param to start the file check without a number.

$extension = ".jpg";
$filename_minus_extension = "some-image";

$filename = checkFile('path-to-directory/', $filename_minus_extension, $extension, "");

This is in no way tested, but the general idea is to use a recursive function. If you have a specific question, feel free to ask and I may update.

Upvotes: 2

kero
kero

Reputation: 10638

You need some kind of loop because you don't know how often you have to check. Then simply change the name in the wanted pattern until there is no file existing with the chosen name

$info = pathinfo($filename); // get details
$name = $info['filename'];
$extension = $info['extension'];
$counter = 0;

while ( file_exists( $name.$counter.'.'.$extension ) )
{
    $counter++;
}

$new_name = $name.$counter.'.'.$extension;

The code is not tested but should work. More importantly I hope you understand what it does ;)

Upvotes: 0

Related Questions