簡體   English   中英

PHP ZipArchive無法在Windows下運行的Ubuntu Linux上提取文件

[英]PHP ZipArchive failing to extract files on Ubuntu Linux running under Windows

我收到了以下警告

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下的PHP 7.1(CentOS)下運行良好。

問題是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);
    }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM