SomeBeginner
SomeBeginner

Reputation: 49

Is this the correct way of checking if a file exists?

I am trying to check if a file (image) exists so I can delete it before uploading the new one. This is what i've tried so far:

foreach (glob("../imgs/" . $name . ".*") as $file) {
    if (file_exists($file)) {
        unlink($file);
    }
}

Is this the correct way of doing this? Do I need to break the loop if a match is found? Would this perform badly if there are a lot of pictures in that folder?

Edit: sorry, i should have mention this: On upload the files get renamed with the user unique id, that's why if a user wants to upload another image i want to replace it with the existing one. (This images are used for profile pictures).

Upvotes: 6

Views: 17174

Answers (2)

Gufran Hasan
Gufran Hasan

Reputation: 9373

If you want to break the loop to add a break statement after unlink() function as:

foreach (glob("../imgs/" . $name . ".*") as $file) {
    if (file_exists($file)) {
        unlink($file);
        break;
    }
}

If you want to check PHP file exists only:

You can use the file_exist() function. This function returns TRUE if the file exists, otherwise, it returns FALSE.

$filename = './file_name.txt';

if(file_exists($filename)){
 echo sprintf('file %s exists',$filename);
}else{
 echo sprintf('file %s does not exist',$filename);
}

If you want to check PHP file exist and readable:

You can use the is_readable() function. The function returns TRUE if the file exists and is readable, otherwise, it returns FALSE.

$filename = './file_name.txt';

if(is_readable($filename)){
 echo sprintf('file %s exists and readable',$filename);
}else{
 echo sprintf('file %s does not exist or is not readable',$filename);
}

If you want to check PHP file exists and writable:

You can use the is_writable() function. The function returns TRUE if the file exists and is writable, otherwise it returns FALSE.

$filename = './file_name.txt';

if(is_writable($filename)){
 echo sprintf('file %s exists and writable',$filename);
}else{
 echo sprintf('file %s does not exist or is not writable',$filename);
}

Upvotes: 10

Manuel Mannhardt
Manuel Mannhardt

Reputation: 2201

Yes, your approach looks good to me. Its most likely faster then grabbing all file names and checking the names using regex.

As Gufran already mentioned in his comment, put a break after the unlink, so the loop does not continue to search. Do this only, if you dont plan to find multiple files, which that name (i.e. test.gif, test.png), then you have to leave it out.

Upvotes: 3

Related Questions