【问题标题】:PHP ZipArchive failing to extract files on Ubuntu Linux running under WindowsPHP ZipArchive 无法在 Windows 下运行的 Ubuntu Linux 上提取文件
【发布时间】:2017-11-16 15:31:35
【问题描述】:

我收到以下警告

PHP Warning:  ZipArchive::extractTo(/mnt/c/some/folder\data.json):
failed to open stream: Invalid argument in /mnt/c/somefile.php on line 54

使用此代码,在运行 PHP 7.1 的 Windows 上使用 Ubuntu 子系统提取任何 zip 文件:

<?php
class someClass
{
    public static function unzip($fn, $to = null)
    {
        $zip = new ZipArchive;

        if (is_null($to)) {
            $to = self::dirname($fn) . DIRECTORY_SEPARATOR . self::filename($fn);
        }

        if (!is_dir($to)) {
            self::mkdir($to, 0755, true);
        }

        $res = $zip->open($fn);
        if ($res === true) {
            $zip->extractTo($to);
            $zip->close();
            return $to;
        } else {
            return false;
        }
    }
}

?>

相同的代码在 Windows 下的 PHP 7.1 和 Linux (CentOS) 下的 PHP 7.1 上运行良好。

【问题讨论】:

  • 只是一个愚蠢的观点:你设置了$ds = DIRECTORY_SEPARATOR;然后从不使用$ds但你确实使用DIRECTORY_SEPARATOR???
  • 哦,是的,在我的原始代码中我有更多的东西,我去掉了大部分不相关的东西,但我一定把它留在了!编辑了我的答案并删除了。

标签: php linux windows ubuntu zip


【解决方案1】:

问题在于 zip 文件名中的正斜杠。

使用以下方法似乎可以解决它:

<?php

class someClass
{
    public static function unzip($fn, $to = null)
    {
        $zip = new ZipArchive;
        $ds  = DIRECTORY_SEPARATOR;
        if (is_null($to)) {
            $to = self::dirname($fn) . $ds . self::filename($fn);
        }

        $to = self::slashes($to);

        if (!is_dir($to)) {
            self::mkdir($to, 0755, true);
        }

        $res = $zip->open($fn);
        if ($res === true) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $ifn = self::slashes($zip->getNameIndex($i));
                if (!is_dir(self::dirname($to . $ds . $ifn))) {
                    self::mkdir(self::dirname($to . $ds . $ifn), 0755, true);
                }

                $fp  = $zip->getStream($zip->getNameIndex($i));
                $ofp = fopen($to . $ds . $ifn, 'w');

                if (!$fp) {
                    throw new \Exception('Unable to extract the file.');
                }

                while (!feof($fp)) {
                    fwrite($ofp, fread($fp, 8192));
                }

                fclose($fp);
                fclose($ofp);
            }
            $zip->close();
            return $to;
        } else {
            return false;
        }
    }

    public static function slashes($fn)
    {
        return str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $fn);
    }
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2019-08-26
    • 2015-07-10
    • 2011-06-06
    相关资源
    最近更新 更多