使用PHP从ZIP存档中查找和显示图像文件的最简单方法

Skr*_*ryn 4 php zip image

function showimage($zip_file, $file_name) {
    if (file_exists($zip_file)) {
        $zip = zip_open($zip_file);
        while ($zip_entry = zip_read($zip)) {
            if (zip_entry_open($zip, $zip_entry, "r")) {
                if (zip_entry_name($zip_entry) == $file_name) {
                    $theimg = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    $theimg = imagecreatefromstring($theimg);
                    if ($theimg !== false) {
                        header('Content-Type: image/jpeg');
                        imagejpeg($theimg);
                        imagedestroy($theimg);
                    }
                    else { echo "Could not create image."; }
                    zip_entry_close($zip_entry);
                }
            }
            else { echo "Could not open."; }
        }
        zip_close($zip);
    }
    else { echo "File not found."; }
}
Run Code Online (Sandbox Code Playgroud)

我正在运行此函数来打开指定的zip文件,然后循环遍历内容以查找指定的文件名,然后从该文件创建图像而无需提取.我有点好奇这个过程是如何系统密集的,如果有一个更整洁/更直接的方式在zip存档中查找文件而不需要循环查看名称是否与给定的文件名匹配.无论如何直接从具有给定名称的zip文件调用文件,假设它存在?

上面的代码有效...我想我只是想看看如何做得更好.如果这是有道理的.

rre*_*ein 5

ZipArchive有一种获取文件而无需实际搜索的方法.

function showimage($zip_file, $file_name) {
    $z = new ZipArchive();
    if ($z->open($zip_file) !== true) {
        echo "File not found.";
        return false;
    }

    $stat = $z->statName($file_name);
    $fp   = $z->getStream($file_name);
    if(!$fp) {
        echo "Could not load image.";
        return false;
    }

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . $stat['size']);
    fpassthru($fp);
    return true;
}
Run Code Online (Sandbox Code Playgroud)