Search code examples
phpglobfile-existsunlink

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).


Solution

  • 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);
    }