我可以在PHP中包含zip文件吗?

Man*_*ngh 3 php

我可以在PHP中包含zip文件中的文件吗?例如,我认为我有一个zip文件 - test.zip和test.zip包含一个名为a.php的文件.现在,我想做的是下面的事情,

包括"test.zip/a.php";

这可能吗?如果可以,任何人都可以提供我的代码片段?如果没有,还有其他任何替代方法吗?

Bor*_*éry 6

$zip = new ZipArchive('test.zip');

$tmp = tmpfile();
$metadata = stream_get_meta_data($tmp);

file_put_content($metadata['uri'], $zip->getFromName('a.php'));

include $metadata['uri'];
Run Code Online (Sandbox Code Playgroud)

为了更进一步,您可能对PHAR存档感兴趣,它基本上是一个Zip存档.

编辑:

使用缓存策略:

if (apc_exists('test_zip_a_php')) {
    $content = apc_fetch('test_zip_a_php');
} else {
    $zip = new ZipArchive('test.zip');
    $content = $zip->getFromName('a.php');
    apc_add('test_zip_a_php', $content);
}

$f = fopen('php://memory', 'w+');
fwrite($f, $content);
rewind($f);
// Note to use such include you need  `allow_url_include` directive sets to `On`
include('data://text/plain,'.stream_get_contents($f));
Run Code Online (Sandbox Code Playgroud)