Search code examples
phppathinfo

How to find the file name or extension from base name


I want to grab the file name from a known base name in PHP.

I've searched and found pathinfo(), but then you already give the file name with base name and extension in the argument.

Also in the pathinfo() docs:

$path_parts = pathinfo('/path/basename');
var_dump($path_parts['extension']);

That's more or less what I need, but the result is :

string '' (length=0)

I want the extension, not an empty string. I know the base name, but I don't know the extension, how do I grab that?


Solution

  • To list file names, knowing only the base, you can use glob. It returns an array because there may be several files with the same base but different extensions, or none at all:

    $files = glob($base.'.*');
    if (!empty($files))
        echo $files[0];