【问题标题】:PHP: $zip->addFile issuesPHP:$zip->addFile 问题
【发布时间】:2015-11-13 09:03:44
【问题描述】:

我编写了一个简单的脚本来将文件添加到存档中。经过多次挠头后,我无法让脚本运行。

我这里有一个 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和destination被传递给它,函数如下。

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。但是没有文件被添加。谁能在这里发现一个明显的错误?

【问题讨论】:

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


    【解决方案1】:

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

    你需要做的是改变这一行:

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

    收件人:

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

    【讨论】:

    • 对可能是愚蠢的回应表示歉意,我只有三周的时间来编码。但是当我遍历 $_POST['File'] 数组时; “foreach($files as $file)” 我不是将单个字符串值传递给 addFile() 吗?
    • 别着急问。我们都从某一点开始。当你遍历 $_POST['File'] 时,你仍然会在 $file 中得到一个数组。因为 $_POST['File'] 是一个二维数组。所以你需要这样做: $file['tmp_name']
    • 我还建议你看看 xdebug 是如何工作的。这样,您就可以调试代码并在运行时检查变量的内容。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多