gpt4 book ai didi

PHP ZipArchive 无法在 Windows 下运行的 Ubuntu Linux 上提取文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:20:05 25 4
gpt4 key购买 nike

我收到以下警告

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 上运行良好。

最佳答案

问题出在 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);
}
?>

关于PHP ZipArchive 无法在 Windows 下运行的 Ubuntu Linux 上提取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44545468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com