如何通过代码(PHP)将文件zip解压缩到之前创建的目录中?

时间:2017-06-02 16:22:35

标签: php unzip

我想使用PHP将文件zip解压缩到之前由代码创建的目录中,但它不起作用。我认为这是一个权限问题,因为如果我手动创建该文件夹它是有效的,如果我从我的脚本创建它,那么它不起作用!

....
$filename = $_FILES["userfile"]["name"];
$source = $_FILES["userfile"]["tmp_name"];
$name = explode(".", $filename);
$target_path = "Apps\\" . $username . "\\" . $name[0]; 

if(move_uploaded_file($source, $target_path))
{       
    $zip = new ZipArchive();
    $x = $zip->open($target_path);
    if ($x === true)
    {
       $zip->extractTo("Apps\\".$username); <- ERROR ON THIS LINE
       $zip->close();
    }
 ....

这是错误:(警告:ZipArchive :: extractTo():没有这样的文件或目录)

我该如何解决?

谢谢!

2 个答案:

答案 0 :(得分:0)

这是你的路径问题,所以更新你的路径然后它将完美地工作,这是演示代码,它可以帮助你上传zip文件,并在zip文件夹的同一文件中解压缩。

<?php
function rmdir_recursive($dir) {
    foreach(scandir($dir) as $file) {
        if ('.' === $file || '..' === $file) continue;
        if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
        else unlink("$dir/$file");
    }

    rmdir($dir);
}

if(!empty($_FILES["file_name"]["name"])) {
    $filename = $_FILES["file_name"]["name"];
    $source = $_FILES["file_name"]["tmp_name"];
    $type = $_FILES["file_name"]["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.";
    }

    $path = dirname(__FILE__).'/';  
    $filenoext = basename ($filename, '.zip');
    $filenoext = basename ($filenoext, '.ZIP');

    $targetdir = $path . $filenoext; 
    $targetzip = $path . $filename; 
    if (is_dir($targetdir))  rmdir_recursive ( $targetdir);

    mkdir($targetdir, 0777);

    if(move_uploaded_file($source, $targetzip)) {
        $zip = new ZipArchive();
        $x = $zip->open($targetzip);
        if ($x === true) {
            $zip->extractTo($targetdir.'/');
            $zip->close();

            unlink($targetzip);
        }
        $message = "Your file is uploaded and unpacked.";
    } else {
        $message = "There is a problem to upload.";
    }
}

?>

<?php if(isset($message)) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
    <label>Upload a zip file to upload: <input type="file" name="file_name" /></label>
    <br />
    <input type="submit" name="submit" value="Upload" />
</form>

希望它能帮助你和其他人

答案 1 :(得分:0)

我已经解决了这个问题:

console.log({ ...new Date(), x: 10 } instanceof Date); // false

这是$ target_path的问题,因为它需要扩展名($ name [1])

感谢所有人!