使用PHP在服务器上解压缩文件时的目录结构

时间:2018-12-02 15:21:25

标签: php ziparchive

我有一个我要在用户注册时创建的网站,我将一个文件解压缩,该文件包含用户配置文件的当前文件夹结构。

文件夹结构以zip /u/folders.zip的形式存储在用户目录中,我认为我正在创建以下结构:

-u
--folders.zip
--newamazingusername
---index.php
---folder1
---folder2
----subfolder1
----subfolder2
---folder3

它正在创建的是这样:

-u
--folders.zip
--newamazingusername
---folders
----index.php
----folder1
----folder2
-----subfolder1
-----subfolder2
----folder3

正在处理文件:

<?php
require_once( "../../assets/inc/connection.php" );

if ( !empty($_GET['email']) && !empty($_GET['username']) ):
    $get_username = $_GET['username'];
    $get_email = $_GET['email'];

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $hash = **[REDACTED CODE] Assume I am Hashing my password properly**
        $sql = "UPDATE users SET username='" . $get_username . "' WHERE email='" . $get_email . "'";
        // use exec() because no results are returned
        $conn->exec($sql);

        $zip = new ZipArchive;
        $fileLocation = $_SERVER['DOCUMENT_ROOT'] . '/u/folders.zip';
        $newfile = $_SERVER['DOCUMENT_ROOT'] . '/u/' . $get_username . '.zip';

        if (!copy($fileLocation, $newfile)) {
            echo "failed to copy";
            header('Location: http://' . $_SERVER['HTTP_HOST'] . '?error=foldercopyfail');
            exit();
        }
        $res = $zip->open($newfile);
        if ($res === TRUE) {
            $zip->extractTo($_SERVER['DOCUMENT_ROOT'] . '/u/' . $get_username);
            $zip->close();

            header('Location: http://' . $_SERVER['HTTP_HOST'] . '/u/' . $get_username );
        } else {
            echo 'doh!';
        }
        unlink($newfile);

        exit();
    } catch(PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }

else :
    header('Location: http://' . $_SERVER['HTTP_HOST'] . '?error=noaccess');
endif;


?>

我需要在用户文件夹根目录的zip中解压缩文件夹。我很确定如果片段是copy()的问题。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试更改此内容:

$res = $zip->open($newfile);
if ($res === TRUE) {
    $zip->extractTo($_SERVER['DOCUMENT_ROOT'] . '/u/' . $get_username);
    $zip->close();

    header('Location: http://' . $_SERVER['HTTP_HOST'] . '/u/' . $get_username );
} else {
    echo 'doh!';
}

与此:

$res = $zip->open($newfile);
if ($res === TRUE) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$newfile."#".$filename, $_SERVER['DOCUMENT_ROOT'] . '/u/' . $get_username . $fileinfo['basename']);
    }
    $zip->close();

    header('Location: http://' . $_SERVER['HTTP_HOST'] . '/u/' . $get_username );
} else {
    echo 'doh!';
}

有关详细说明,请阅读extractTo()的php文档页面上的user contributed note