Home » Php » PHP check file exists without knowing the extension

PHP check file exists without knowing the extension

Posted by: admin April 23, 2020 Leave a comment

Questions:

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 ?

How to&Answers:

You would have to do a glob():

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

and see whether $result contains anything.

Answer:

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

Answer:

Did you know about the PHP filetype function?
http://php.net/manual/en/function.filetype.php

Or otherwise is_file()
http://www.php.net/manual/en/function.is-file.php