PHP Upload and Extract Zip

前提是你 提交于 2020-01-07 07:28:40

问题


I'm trying to run a script that allows the upload of a .zip and extracts the contents. I grabbed a sample code online that is supposed to work and added a class at the beginning b/c my ISP doesn't have the zip functionality compiled in correctly.

I've left a big comment in the middle where I'm getting stuck. Not sure if this has anything to do with it running on IIS?

The .zip file gets uploaded where I'd expect it to, and I'm manually able to ftp it back and extract the files. I'm looking to extract the files here, loop over them, if they're image files, then add them to a database of gallery images... first things first though. Need to understand why I'm not seeing the contents of the zip...

<?php // need this bc of ISP settings
require($_SERVER['DOCUMENT_ROOT']."/_classes/ZipArchive.php");
?><?php
if($_FILES["zip_file"]["name"]) {
    $filename = $_FILES["zip_file"]["name"];
    $source = $_FILES["zip_file"]["tmp_name"];
    $type = $_FILES["zip_file"]["type"];

    $name = explode(".", $filename);
    $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
    foreach($accepted_types as $mime_type) {
         if($mime_type == $type) {
             $okay = true;
             break;
          } 
    }
    $continue = strtolower($name[1]) == 'zip' ? true : false;
    if(!$continue) {
        $message = "The file you are trying to upload is not a .zip file. Please try again.";
    }

    // I set up the _TEST dir with 777 permissions
    $target_path = $_SERVER['DOCUMENT_ROOT']."/_TEST/".$filename;
    if(move_uploaded_file($source, $target_path)) {
        $zip = new ZipArchive();
        $x = $zip->open($target_path);

        // **********************************************************
        // $x returns an error here
        // code: ER_OPEN
        // http://php.net/manual/en/function.ziparchive-open.php
        // Not sure why?????
        // **********************************************************

        if ($x === true) {
           $zip->extractTo($_SERVER['DOCUMENT_ROOT']."/_TEST/");
           $zip->close();
           unlink($target_path);
           $message = "Your .zip file was uploaded and unpacked.";
        }
        else {
           $message =  'failed';
        }
    } else {    
        $message = "There was a problem with the upload. Please try again.";
    }
}
?>

回答1:


Not a solution but a workaround: do you have the control of the machine? If so, install 7-zip (on Windows) or unzip, use system('unzip ...') or system('7z ...') to extract the zip archive.




回答2:


ISP installed the necessary components for zip to work so all is well now. Thanks @timdream for an alternative approach.



来源:https://stackoverflow.com/questions/6122137/php-upload-and-extract-zip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!