开发者

PHP unpack zip and insert content into database

开发者 https://www.devze.com 2023-04-04 10:11 出处:网络
I need to be able to extract a zip file, and insert the names of the files in the zip file into a database.

I need to be able to extract a zip file, and insert the names of the files in the zip file into a database.

I've searched around, and f开发者_JAVA百科ound multiple scripts to unpack a zip file, but it seems that I'm not able to get the individual filenames of the files in the zip file.


I would probably suggest to use two system calls:

1) unzip to tmp folder 2) read files from that folder

(updated full working script):

<?php

if (isset($_POST["fsubmit"])){
    echo "<pre>";
    var_dump($_POST);
    var_dump($_FILES);
    $tmp_dir = "tmp/" . microtime(true);
    if (!file_exists($tmp_dir)){
        mkdir($tmp_dir);
    }
    if (is_uploaded_file($_FILES["file"]["tmp_name"])){
        move_uploaded_file($_FILES["file"]["tmp_name"], $tmp_dir . "/a.zip");
        exec("unzip -z -j $tmp_dir $tmp_dir" . "/a.zip");
        exec("ls $tmp_dir", $out);
        echo "Files in the archive:\n";
        foreach ($out as $file){
            $file = trim($file);
            echo "File: $file,", filesize($tmp_dir . "/" . $file)."b\n";
        }
        exec("rm -rf $tmp_dir");
    }
} else {
?>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="fsubmit" value="upload">
</form>
<?
}

Pre-requisites
0) will work if you are under unix/linux/mac (won't work under windows)
1) create test.php and paste in it the code above
2) make sure in the same folder where test.php, is folder tmp
3) make sure apache user can write that folder (e.g. chmod 777 tmp)
4) make sure your php allows file uploads
5) make sure your server has "unzip" command line tool

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消