34

I need to check if a file exists but I don't know the extension.

IE I would like to do:

if(file_exists('./uploads/filename')):
 // do something
endif;

Of course that wont work as it has no extension. the extension will be either jpg, jpeg, png, gif

Any ideas of a way of doing this without doing a loop ?

BenMorel
  • 30,280
  • 40
  • 163
  • 285
Lee
  • 17,158
  • 23
  • 71
  • 97

2 Answers2

69

You would have to do a glob():

$result = glob ("./uploads/filename.*");

and see whether $result contains anything.

Pekka
  • 418,526
  • 129
  • 929
  • 1,058
7

I've got the same need, and tried to use glob but this function seems to not be portable :

See notes from http://php.net/manual/en/function.glob.php :

Note: This function isn't available on some systems (e.g. old Sun OS).

Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

It also more slower than opendir, take a look at : Which is faster: glob() or opendir()

So I've made a snippet function that does the same thing :

function resolve($name) {
    // reads informations over the path
    $info = pathinfo($name);
    if (!empty($info['extension'])) {
        // if the file already contains an extension returns it
        return $name;
    }
    $filename = $info['filename'];
    $len = strlen($filename);
    // open the folder
    $dh = opendir($info['dirname']);
    if (!$dh) {
        return false;
    }
    // scan each file in the folder
    while (($file = readdir($dh)) !== false) {
        if (strncmp($file, $filename, $len) === 0) {
            if (strlen($name) > $len) {
                // if name contains a directory part
                $name = substr($name, 0, strlen($name) - $len) . $file;
            } else {
                // if the name is at the path root
                $name = $file;
            }
            closedir($dh);
            return $name;
        }
    }
    // file not found
    closedir($dh);
    return false;
}

Usage :

$file = resolve('/var/www/my-website/index');
echo $file; // will output /var/www/my-website/index.html (for example)

Hope that could helps someone, Ioan

Community
  • 1
  • 1
Ioan Chiriac
  • 91
  • 1
  • 3