mattegener mattegener - 1 month ago 6
PHP Question

PHP Checking if a file exists in a directory

I'm creating a file uploader, and it checks to see if a file exists or not in a directory. If it does exist, I must come up with a new name for the file (I.E file.txt -> file1.txt). Not sure why, but it keeps on generating errors. Here's my code. Hopefully it isn't something painfully obvious.

$directory = "files/";
$name = $_FILES['filename']['name'];
$valid_name = true;
$counter = 0;
if(file_exists($directory . $_FILES['filename']['name'])) {
$valid_name = false;
}
while(!$valid_name){
$name = $_FILES['filename']['name'] . $counter;
if(file_exists($directory . $name)){
counter++;
}
}

Answer

Your code is wrong. This is much simpler and easier to understand.

$directory = "files/";
$counter = 0;
$name = $_FILES['filename']['name'];
while(file_exists($directory . $name)){
    $counter++;
    $name = $_FILES['filename']['name'] . $counter;
}

Also your code does not generate file.txt -> file1.txt but file.txt -> file.txt1 so does this one. To generate it properly play with the extension and the name.

Comments