How to retrieve file from folder when you don't know file extension?

Viewed 62

I want to retrieve a file from a specific folder on my server.

I know that the file is at the path:

Fodler/Sub-folder/file

But I do not know if it is a .jpg or a .png.

How do I succesfully find ou tif the path is

Fodler/Sub-folder/file.jpg

or

Fodler/Sub-folder/file.png
3 Answers

In PHP

array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )

returns an array of files and directories from the directory. If there is only one file in the directory, then the array will have size 1

You can use glob(), with the asterisk * as wildcard symbol:

// if glob() does not return false or an empty array
if( !empty( $files = glob( 'Folder/Sub-folder/file.*' ) ) ) {
  // echo the first found file path that matches the pattern
  echo $files[ 0 ];
}

Or, if you want to limit the search to only .jpg and .png (I initially glossed over that requirement), you can use the brace syntax {}, with the GLOB_BRACE flag.

if( !empty( $files = glob( 'Folder/Sub-folder/file.{jpg,png}', GLOB_BRACE ) ) ) {
  // echo the first found file path that matches the pattern
  echo $files[ 0 ];
}

And if you only want to know the extension use pathinfo():

echo pathinfo( $files[ 0 ], PATHINFO_EXTENSION );

Search all files based on filename until .ext, then search for desired image extension within the path. Then re-index the $matches array (since it carries the the index it has within the glob result), and get path by index 0;

$result = glob ("./directory/image.*");
$search = '.png';
$matches = array_values(array_filter($result, function($var) use ($search) { return preg_match("/\b$search\b/i", $var); }));
$filePath = $matches[0];
$ext = pathinfo( $filePath, PATHINFO_EXTENSION );
var_dump($filePath,$ext);

Depending if you need to carry out a certain action on either .png or .jpg file, the first $result should help you loop through the files.

Related