【问题标题】:Wordpress - Zip archive force downloadWordpress - Zip归档强制下载
【发布时间】:2023-04-09 13:05:01
【问题描述】:

我试图让用户有可能在 wordpress 中下载档案,但在创建档案后下载不会开始。我可以看到我的存档已创建,她在服务器上可用。这是我的代码:

我的“图书馆”

<?php
    function create_zip($files = array(), $destination = '', $overwrite = false) {
        if(file_exists($destination) && !$overwrite) {
            return false;
        }
        $valid_files = array();
        if(is_array($files)) {
            foreach($files as $file) {
                if(file_exists($file)) {
                    $valid_files[] = $file;
                }
            }
        }
        if(count($valid_files)) {
            $zip = new ZipArchive();
            if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
                return false;
            }
            foreach($valid_files as $file) {
                $zip->addFile($file,$file);
            }
            $zip->close();
            return file_exists($destination);
        } else {
            return false;
        }
    }

?>

wordpress调用的函数:

<?php

    require "zip.php";
    $customwp = plugins_url().'/customwp/';
    wp_enqueue_style('tutoriels',$customwp.'css/tutoriels.css');
    wp_enqueue_script('tutoriels',$customwp.'js/tutoriels.js',array('jquery'),'1.0',true);

    ob_start();

    $dir = ABSPATH . 'wp-content/plugins/customwp/';
    $files_to_zip = array(
        $dir.'zip.php'
    );
    $archive_name = "archive.zip";
    $result = create_zip($files_to_zip, $archive_name);

    header('Content-Transfer-Encoding: binary'); //Transfert en binaire (fichier).
    header('Content-Disposition: attachment; filename="archive.zip"'); //Nom du fichier.
    header('Content-Length: '.filesize($archive_name)); //Taille du fichier.
    readfile($archive_name);

    $output_string=ob_get_contents();
    ob_end_clean();
    return $output_string;

?>

如果你能帮助我,不要犹豫,试试吧! 最好的问候

【问题讨论】:

    标签: php wordpress zip archive


    【解决方案1】:

    最后一行,你有的地方

    return $output_string;
    

    应该是

    echo $output_string;
    

    另外,虽然在这种情况下它似乎不会影响您的代码,但请记住,输出缓冲不会缓冲您的 header() 调用,它们会立即发送。见php page about it

    此函数将打开输出缓冲。当输出缓冲处于活动状态时,脚本(除了标题)不会发送任何输出,而是将输出存储在内部缓冲区中。

    【讨论】:

    • Arf 是的,我忘记了,所以你看到解决方案了吗,我希望它能够在短代码中调用我的函数:/。这就是我使用输出缓冲的原因。即使使用 echo 存档也不会发送。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 2023-03-07
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多