Reputation: 95
Can I include a file from a zip file in PHP? For example consider I have a zip file - test.zip and test.zip contains a file by the name a.php. Now, what I would like to do is something like below,
include "test.zip/a.php";
Is this possible? If it is can anyone provide me a code snippet?? If not, id there any other alternative to do this??
Upvotes: 3
Views: 1687
Reputation: 47604
$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'];
To go further, you may be interested in PHAR archive, which basically a Zip archive.
Edit:
With a cache strategy:
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));
Upvotes: 6
Reputation: 7297
Are you all sure? According to the phar extension, phar is implemented using a stream wrapper, so they can just call
include 'phar:///path/to/myphar.phar/file.php';
But there also exists stream wrappers for zip, see this example, where they call:
$reader->open('zip://' . dirname(__FILE__) . '/test.odt#meta.xml');
To open the file meta.xml in the zip-File test.odt
(odt-files are only zip-files with another extension).
Also in another example they directly open a zip file via stream wrapper:
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
I have to admit, I do not know how directly it works.
I would try calling
include 'zip:///path/to/myarchive.zip#file.php';
Unlike the phar wrapper the zip wrapper seams to require a sharp, but you can also try it with a slash. But it’s also just an idea from reading the docs.
If it does not work, you can use phars of course.
Upvotes: 2