'glob() Multiple files have the same file name with different file extensions

Multiple files have the same file name with different file extensions

Files:

  • media/
    • name.jpg
    • name.png
    • name.gif
    • name2.png

Find files with the same name and get array with extensions:

   $file = null;
   $file = glob('*/*/media/name.*');
   rsort($file);
   echo'<pre>'; print_r($file); echo'</pre>';

expected:

Array
(
    [0] => jpg
    [1] => png
    [2] => gif
)

unexpected:

Array
(
    [0] => media/name.jpg
    [1] => media/name.png
    [2] => media/name.gif
)
php


Solution 1:[1]

You need to use Glob function

$name= "hello";

$files = glob("/path/to/files/$name.*"); // Will find all file with hello.extension

if (count($files) > 0){
foreach ($files as $file)
 {
    $info = pathinfo($file);
    echo "File found: extension ".$info["extension"]."<br>";
 }
 }else{
  echo "No file name exists called $name."
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Simone Rossaini