Search code examples
phpglob

PHP glob() with few extensions


I want to know when I have, in directory, any file with extension like : doc, docx, pdf, rtf.

My script is working for one extension

$ebook_filepath1 = glob($album_filepath . '*.txt') or array();
$ebook_count1 = count($ebook_filepath1);

if ($ebook_count1 != 0) {

echo "yes";

} else {

echo "no";

}

but for more that one not

$ebook_filepath1 = glob($album_filepath . '*.{txt,pdf,doc}') or array();

another problem is - how to use in this code the variable f.ex. named $extensions

$extensions = array('doc', 'docx', 'epub', 'mobi', 'pdf', 'rtf');

Solution

  • You need to use glob() (you got that part right) with the GLOB_BRACE flag :

    print_r(glob("*.{gz,zip}",GLOB_BRACE));
    

    You could then easily build your string from your variable array with implode() :

    $extensions = array('doc', 'docx', 'epub', 'mobi', 'pdf', 'rtf');
    print_r(glob("*.{".implode(',',$extensions)."}",GLOB_BRACE));