Search code examples
phpzipphp-ziparchive

ZipArchive::getFromName does not find filename


Any idea what I am doing wrong here? It keeps dying with 'bye bye'. There is an index.php file inside the zip archive.

$zip = new ZipArchive;
$zip->open($source);
$test = $zip->getFromName('index.php');
if(!$test) {
    die('bye bye');
} else {
    die($test);
}

Solution

  • Well, the first thing you should do is ensure that you've opened it okay since that can fail as well:

    $zip = new ZipArchive;
    $rc = $zip->open($source);
    if ($rc === TRUE) {
        $test = $zip->getFromName('index.php');
        $zip->close();
        if(!$test) {
            die('bye bye');
        } else {
            die($test);
        }
    } else {
        die("could not open: " . $rc);
    }
    

    Other than that, make sure you are absolutely certain that your file specification is correct. If necessary, you can use getNameIndex to enumerate the entries one at a time, printing out their names in the process, something like:

    $zippy = new ZipArchive();
    $zippy->open($source);
    for ($i = 0; $i < $zippy->numFiles; $i++) {
        echo $zippy->getNameIndex($i) . '<br />';
    }
    $zippy->close();
    

    And I'm assuming that I would be wasting my time telling you to check the value of $source. You may want to check, just in case.