使用ZipArhive将文件压缩为URL

时间:2015-12-08 12:52:36

标签: php pdf ziparchive

我有一个WordPress网站,用户可以下载一个或多个pdf文件。到目前为止,我只是在不使用任何WordPress功能的情况下进行编码,并将文件放在我的计算机上。但是在将来,我希望能够使用高级自定义字段(或类似的东西)添加文件,这意味着我不会将文件放在文件夹中,而是必须使用URL。至少我觉得呢? 当我使用相同的代码,但使用URL(见下文)时,它不起作用。

那么如何使用ZipArchive从URL创建zip文件?

<?php
    if(isset($_POST['createzip']))
    {
        $files = $_POST['files'];
        $zipname = time().".zip"; // Zip name
        $zip = new ZipArchive(); // Load zip library
        $zip->open($zipname, ZipArchive::CREATE);
        foreach ($files as $file) {
            $zip->addFile($file);
        }
        $zip->close();
    // push to download the zip
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename='.$zipname);
        header('Content-Length: ' . filesize($zipname));
        readfile($zipname);
    }
?>

<h1> hej här kan du zippa lite filer</h1>

<form name="zips" method="post">
    <input type="checkbox" name="files" value="http://www.unstraight.org/wp-content/uploads/2015/08/seger3.jpg">
    <p>Seger</p>
    <input type="checkbox" name="files" value="http://www.unstraight.org/wp-content/uploads/dlm_uploads/2015/12/Ovningar-medelsvara.pdf">
    <p>Övningar </p>
    <input type="checkbox" name="files" value="http://www.unstraight.org/wp-content/uploads/2015/07/User-Agreement-.pdf">
    <p>Medlemskort </p>
    <input type="checkbox" name="files[]" value="men.pdf">
    <p>Män och Jämställdhet </p>
    <input type="submit" name="createzip" value="Download as ZIP">
</form>

1 个答案:

答案 0 :(得分:0)

您可以从网址中检索文档,然后使用ZipArchive::addFromString

文档:http://php.net/manual/en/ziparchive.addfromstring.php

代码可能如下所示:

foreach ($files as $file) {
    if(preg_match('/^https?\:/', $file)) {

        // Looks like a URL

        // Generate a file name for including in the zip
        $url_components = explode('/', $file);
        $file_name = array_pop($url_components);

        // Make sure we only have safe characters in the filename
        $file_name = preg_replace('/[^A-z0-9_\.-]/', '', $file_name);

        // If all else fails, default to a random filename
        if(empty($file_name)) $file_name = time() . rand(10000, 99999);

        // Make sure we have a .pdf extension
        if(!preg_match('/\.pdf$/', $file_name)) $file_name .= '.pdf';

        // Download file
        $ch = curl_init($file);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_content = curl_exec($ch);
        curl_close($ch);

        // Add to zip
        $zip->addFromString($file_name, $file_content);

    } else {

        // Looks like a local file
        $zip->addFile($file);

    }
}