Search code examples
phpglob

PHP Glob check if a file exists


I am using the following function to understand if a file exists using glob

function eSetSplash($eID, $catID) {
    $splashscreen = URL_ICONSET . $catID . "/default_splashscreen.png";
    if (file_exists(glob(DIRECTORY_PATH_UPLOADS . md5($eID) . 'app/splashscreen_event.*')))
        $splashscreen = glob(SITE_URL .'/upload/' . md5($eID) . 'app/splashscreen_event.*');
    return $splashscreen;
}

I have two problems:

<b>Warning</b>:  file_exists() expects parameter 1 to be a valid path

And also I am not sure if doing the following way will actually return the file path or if it is just my imagination :D

$splashscreen = glob(SITE_URL .'/upload/' . md5($eID) . 'app/splashscreen_event.*');

Solution

  • glob gets all filenames that match your pattern and it returns an array containing these names.

    So instead of using file_exists (which expects a file path string and not an array), you can simply use something like:

    $files = glob(...);
    if (count($files) > 0)
    

    to see if any files were found.

    If you are sure your pattern will return only one file-name or less, you can use $files[0] or reset($files) to get the first element (if the condition is met...).