Skip to content

Instantly share code, notes, and snippets.

@vlepeule
Created November 15, 2016 11:30
Show Gist options
  • Save vlepeule/b2f2dcc2e6b353c203729d6c82931fb8 to your computer and use it in GitHub Desktop.
Save vlepeule/b2f2dcc2e6b353c203729d6c82931fb8 to your computer and use it in GitHub Desktop.
Extract ZIp from php
<?php
// /!\ This is a draft, use it with caution
$allowed_ips = array(
'xxx.xxx.xxx.xxx', // Your IP
'127.0.0.1',
'fe80::1',
'::1'
);
// Grant access to allowed IP only
if (
!(in_array(@$_SERVER['REMOTE_ADDR'], $allowed_ips))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file.');
}
class PHP_Zip_Exctractor
{
private $filename;
public function __construct($filename)
{
$this->filename = $filename;
}
public function processExctraction()
{
$fileinfo = pathinfo($this->filename);
if (!is_file($this->filename)) {
throw new Exception('File not exists.');
}
if ($fileinfo['extension'] !== 'zip') {
throw new Exception('File is not a ZIP.');
}
$zip = new ZipArchive;
$zip->open( $this->filename );
$zip->extractTo( './' );
$zip->close();
return true;
}
public static function listFolder($path = "./")
{
$rep = opendir( $path );
$filenames = array();
chdir( $path );
while ( $filename = readdir( $rep ) ) {
if ( $filename != '..' && $filename != '.' && $filename != '' ) {
$fileinfo = pathinfo($filename);
if ( $filename && $fileinfo['extension'] === 'zip') {
$filenames[] = $filename;
}
}
}
closedir( $rep );
return $filenames;
}
public function getFilename()
{
return $this->filename;
}
public function setFilename($filename)
{
$this->filename = $filename;
return $this;
}
}
$filename = filter_input(INPUT_GET, 'filename');
if (!!$filename) {
try{
$extractor = new PHP_Zip_Exctractor($filename);
$extractor->processExctraction();
echo $extractor->getFilename() . " successfully extracted !";
}catch(Exception $e){
echo "An error occured !\r\n";
echo $e->getMessage();
die();
}
}else{
$folderList = PHP_Zip_Exctractor::listFolder();
if (!empty($folderList)) {
echo "Click on the file to extract it";
echo "<ul>";
foreach (PHP_Zip_Exctractor::listFolder() as $filename) {
echo "<li><a href=?filename=$filename>$filename</a></li>";
}
echo "</ul>";
}else{
echo "No file found.";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment