PHP:$ zip-> addFile问题

时间:2015-11-13 09:03:45

标签: php php-5.6 php-zip-archive

我编写了一个简单的脚本来将文件添加到存档中。经过多次努力之后,我无法让脚本工作。

我这里有一个php文件,它从复选框中读取,复选框中选中的文件被添加到数组$ file。

$path = ('a path');
$dir = scandir('another path');

    if(isset($_POST["submit"])){
    if(!isset($_POST["File"])){
        echo 'A file must be selected to archive it';
        } else { 
            require_once('zip_function.php');
            $file = $_POST['File'];
            $goZipper = goZipper($file, $path);
            if($goZipper == false) {
                echo ("Error");
            } else { 
                echo ("Success");
            }
        }   
    }

调用函数goZipper并将$ file和目标传递给它,函数在下面。

function goZipper($files, $destination = '',$overwrite = true) {
    if(file_exists($destination) && !$overwrite) {
        echo"File exists";
        return false; 
        }
    if(count($files)){
        $zip = new ZipArchive();
            if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true){
                echo"Error opening destination";
                return false;
            } 
            foreach($files as $file){
                $zip->addFile($file,basename($file));

                    echo("<pre>");
                    var_dump($zip);
                    exit();

            }
            $zip->close();
            return file_exists($destination);
            }
            else{
                return false;
            }
    }

每次调用函数时,函数都返回true。但是没有添加任何文件。谁能在这里发现一个明显的错误?

2 个答案:

答案 0 :(得分:2)

ZipArchive::addFile()期望第一个参数是包含文件名的字符串。但是你将$ _POST [&#39; File&#39;]的值传递给它,这是一个数组,因为$ _POST [&#39; File&#39;]是一个二维数组。
See here for the contents of $_POST['File'].

您需要做的是更改此行:

$zip->addFile($file,basename($file));

要:

$zip->addFile($file['tmp_name'],$file['name']);

答案 1 :(得分:1)

Zip::addFile需要第一个参数中的绝对路径,第二个参数是PhpDOc中提到的文件名

$zip->addFile('/path/to/index.txt', 'newname.txt');

并确保您使用绝对路径获取$file变量。如果您要从浏览器上传文件,那么您应该在第一个参数的$_FILE['file']['tmp_name']方法中使用$zip->addFile