Nick Briz
Nick Briz

Reputation: 1977

extract only specific file types from zip with php

I'm creating a simple webapp my students can use to upload their projects (as a .zip file) to my server. This app takes the .zip > unzips it > displays a link to their web-project.

I'm using a php function like this, to extract the zip file:

function openZip($file_to_open) {  
    global $target;  

    $zip = new ZipArchive();  
    $x = $zip->open($file_to_open);  
    if($x === true) {  
        $zip->extractTo($target);  
        $zip->close();  

        unlink($file_to_open);  
    } else {  
         die("There was a problem. Please try again!"); 
    } 
}

is it possible to check the type of the files being extracted and only allow specific file types to get unzipped? Not that I don't trust my students... just want to make sure nothing malicious makes its way to my server.

my students will be uploading simple web projects, so I only want to allow .html, .css and .js (as well as image file types, and directories) to be extracted.

Upvotes: 1

Views: 2735

Answers (2)

SmartGuyz
SmartGuyz

Reputation: 69

You can always try finfo_file() like this:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, "yourfile.zip");
finfo_close($finfo);

Upvotes: 0

DOOManiac
DOOManiac

Reputation: 6284

Check out ZipArchive::getFromName to pull just 1 file from the Zip by filename. You may also want to take a look at ZipArchive::getFromIndex

$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE)
{
    echo $zip->getFromName('testfromfile.php');
    $zip->close();
}
else
{
    echo 'failed';
}

Upvotes: 1

Related Questions