ntan ntan - 2 months ago 13
PHP Question

php check if file exist on multiple folders at the same time

when i want to check if a file exist and if exist add a suffix i use the following code which is working fine

$increment = ''; //start with no suffix
while(file_exists($_SERVER["DOCUMENT_ROOT"]."/".$file_name . $increment . '.' . $extension))
{
$increment++;
}
$final_name = $file_name . $increment. '.' . $extension;


Now i have to check if the file exist in more that one folder and the names of the folders are in an array (and i can add or remove folders from this array);

$folders[] = "thumb";
$folders[] = "medium";
$folders[] = "large";
$folders[] = "xlarge";


Now i have to check if the file exist in all these folders.

If the file exist in one of this folders i have to add a suffix
check again until the file does not exist in all of these folders

Any help appreciated.

HZS HZS
Answer

I'll agree with @arkascha 's view that if the file is for internal use, using file name with unique hash will be better.

But if it's necessary, Try use foreach() to check those prefix in your array at once.

function files_suffix_exists($file_name, $folders){
    $root = $_SERVER["DOCUMENT_ROOT"];
    if(file_exists($root."/".$file_name . '.' . $extension){
        return true;
    }
    foreach($folders as $folder){
        if(file_exists($root."/".$folder."/".$file_name . '.' . $extension){
            return true;
        }
    }
    return false;
}

$folders[] = "thumb";
$folders[] = "medium";
$folders[] = "large";
$folders[] = "xlarge";


$increment = ''; //start with no suffix
while(files_suffix_exists($file_name, $folders))
   $increment++;
   $file_name .= $increment;
}

$final_name = $file_name . '.' . $extension;
Comments