Search code examples
phpwildcardunzip

Why I cannot unzip a file using wildcards in PHP?


I am trying to extract a zip-file using a wildcard. The point of this is to find out the said file. The file has a changing name after today's date when I download it: test-18-02-2016.zip. I tried like this:

<?php
    $myFile = 'C:/Users/Acer/Downloads/test*.zip';
    $zip = new ZipArchive();
    if($zip->open($myFile) === true) {
        $zip->extractTo('C:/Users/Acer/Downloads/');
        $zip->close();
        echo 'ok';
    } else {
        echo 'NOT ok!';
    }

I am getting NOT ok ..of course, but when i switch on to test-18-02-2016.zipI get ok. Any help to figure out why and how to resolve this is very appreciate it.


Solution

  • A ZipArchive can only represent one file at a time. If you absolutely must use wildcards, consider passing the wildcard string into glob() and using the results it returns.

    For example:

    $myFileList = glob('C:/Users/Acer/Downloads/test*.zip');
    foreach ($myFileList as $myFile) {
        echo 'Unzipping ' . $myFile . PHP_EOL;
    
        $zip = new ZipArchive();
        if($zip->open($myFile) === true) {
            $zip->extractTo('C:/Users/Acer/Downloads/');
            $zip->close();
            echo 'ok';
        } else {
            echo 'NOT ok!';
        }
    }