2015-09-21 60 views
1

我在这里拉我的头发。我花了上个星期试图弄清楚为什么ZipArchive extractTo方法在Linux上的行为与在我们的测试服务器(WAMP)上的行为不同。Linux PHP ExtractTo返回整个路径而不是文件结构

下面是该问题的最基本的例子。我只是需要提取具有以下结构的拉链:

my-zip-file.zip 
-username01 
    --filename01.txt 
    -images.zip 
     --image01.png 
    -songs.zip 
     --song01.wav 
-username02 
    --filename01.txt 
    -images.zip 
     --image01.png 
    -songs.zip 
     --song01.wav 

下面的代码将提取根zip文件,并保持结构我WAMP的服务器上。我不需要担心提取子文件夹。

<?php 
if(isset($_FILES["zip_file"]["name"])) { 
$filename = $_FILES["zip_file"]["name"]; 
$source = $_FILES["zip_file"]["tmp_name"]; 
$errors = array(); 

$name = explode(".", $filename); 

$continue = strtolower($name[1]) == 'zip' ? true : false; 
if(!$continue) { 
    $errors[] = "The file you are trying to upload is not a .zip file. Please try again."; 
} 

$zip = new ZipArchive(); 

if($zip->open($source) === FALSE) 
{ 
    $errors[]= "Failed to open zip file."; 
} 

if(empty($errors)) 
{ 
    $zip->extractTo("./uploads"); 
    $zip->close(); 
    $errors[] = "Zip file successfully extracted! <br />"; 
} 

} 
?> 

从上面的WAMP脚本输出正确提取它(保持文件结构)。

当我我们生活的服务器上运行这个输出是这样的:

--username01\filename01.txt 
--username01\images.zip 
--username01\songs.zip 
--username02\filename01.txt 
--username02\images.zip 
--username02\songs.zip 

我想不通为什么它的行为不同的活的服务器上。任何帮助将不胜感激!

+0

嘿@Zachary。我不清楚究竟是什么问题。你想在两个系统中递归提取zip吗? –

+0

感谢您的回复!问题是,当我解压zip文件时,linux破坏了文件结构.....我相信它与反斜杠有关,但我无法弄清楚如何使用正斜杠来保留目录结构 – Zachary

+0

我认为我遇到了这个问题:斜杠成为Linux上文件名的一部分。是吗? –

回答

0

要修复文件路径,您可以遍历所有提取的文件并将其移动。

你的循环中假设了你有一个包含文件路径的变量$source提取的所有文件(例如:username01\filename01.txt),你可以做到以下几点:

// Get a string with the correct file path 
$target = str_replace('\\', '/', $source); 

// Create the directory structure to hold the new file 
$dir = dirname($target); 
if (!is_dir($dir)) { 
    mkdir($dir, 0777, true); 
} 

// Move the file to the correct path. 
rename($source, $target); 

编辑

您应该检查了在执行上述逻辑之前,在文件名中使用反斜杠。用迭代器,你的代码应该看起来像这样:

// Assuming the same directory in your code sample. 
$dir = new DirectoryIterator('./uploads'); 
foreach ($dir as $fileinfo) { 
    if (
     $fileinfo->isFile() 
     && strpos($fileinfo->getFilename(), '\\') !== false // Checking for a backslash 
    ) { 
     $source = $fileinfo->getPathname(); 

     // Do the magic, A.K.A. paste the code above 

    } 
} 
+0

仍然做同样的事情。我不认为mkdir函数和重命名函数做了什么。我会发布我的代码,但它不适合评论。 – Zachary

+0

@Zachary,你可以添加你试过的代码来更新你的问题。 –

+0

我可以得到您的电子邮件地址吗?上面的代码比实际代码更概念化。我想向您发送实际的代码。 – Zachary

相关问题