PHP readfile下载超时

时间:2016-02-05 22:19:28

标签: php readfile ziparchive

我的PHP脚本不断崩溃/超时,大概是因为readfile。 我的目标是生成zip,让用户下载它,然后删除zip。

代码:

<?php

if(isset($_POST['version']) && isset($_POST['items']) && isset($_POST['identifier'])) {

$identifier = $_POST['identifier'];
$version = $_POST['version'];
$tmp = dirname(__FILE__) . "/download/";
$zipfile = $tmp . $identifier . ".zip";
$name = "Program v" . $version . ".zip";
$path = dirname(__FILE__) . "\\download\\template\\" . $version;

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path),
    RecursiveIteratorIterator::LEAVES_ONLY
);

$zip = new ZipArchive();

if ($zip->open($zipfile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {

    foreach ($files as $name => $file) {
        // Skip directories (they would be added automatically)
        if (!$file->isDir()) {
            // Get real and relative path for current file
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($path) + 1);

            //echo "adding " . $file . " as " . $relativePath;
            // Add current file to archive
            $zip->addFile($file, $relativePath);
        }
    }

    $zip->close();
} else {
    die('Error: Unable to create zip file');
}

// Stream the file to the client
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($zipfile));
header('Content-disposition: attachment; filename="'.$name.'"');
readfile($zipfile);
exit;

}

在下载部分之前一切正常。 zip文件在服务器上生成正常,当试图下载它时,它崩溃了。

有时它会在我的日志中显示错误,这告诉我它需要一个有效的路径并且给出了一个对象。即使它严格地输出一个字符串(路径)。

注意:该文件小于300 KiB,所以我非常怀疑网络服务器的内存不足。

我很失落,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

问题在于生成ZIP文件。 addFile方法需要文件路径作为其第一个参数,而不是对象。参见文档:

  

bool ZipArchive::addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] )

http://php.net/manual/en/ziparchive.addfile.php

因此,在您的情况下,正确的表达式将是:

$zip->addFile($filePath, $relativePath);