Question

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?

Was it helpful?

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];

OTHER TIPS

If file has an extension you can get it like this

$file_name = 'test.jpg';
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
echo $ext;  // output:jpg

Example: To scan all files in images directory and show if ext is allowed or not

$image_path = __DIR__ . '/images/';
$files = scandir($image_path);
$allowed_images = array('jpg', 'jpeg', 'gif', 'png');
foreach ($files as $file_name) {
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);
    if (in_array($ext, $allowed_images)) {
        echo $ext . ' allowed<br>';
    } else {
        echo $ext . ' not allowed<br>';
    }
}

You could use:

$ext = end(explode('.',$filename));

Note: it's not secure to rely on this extension to determine the file type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top