PHP: Große Datei downloaden (als Stream)

edit | delete

Autor: Ralf v.d.Mark

eingetragen: Freitag, 07. August 2020 um 12:42 Uhr (32/2020 Kalenderwoche)

geändert: Freitag, 07. August 2020 um 15:12 Uhr (32/2020 Kalenderwoche)

Keywords: attachment header byte stream Stück download runterladen groß file

Kategorien: Browser, PHP-ZF, PHP, PhpOffice,

Text:

Große Datei als Stream, byte für byte, Stück für Stück downloaden

Quellcode:  

function DownloadGrosseDatei($dateiUndPfad)
{
    //Header manipulieren
    header('Content-Type: application/octet-stream; charset=UTF-8');
    //Jetzt noch Dateiname und Typ festlegen:
    header('Content-Disposition: attachment; filename="'.basename($dateiUndPfad).'"');
    //Datei als Stream ausgeben
    downloadStueckweise($dateiUndPfad);
    exit();//Stopp!!
}//ENDE: function DownloadGrosseDatei(...)

define('STUECK_GROESSE', 1024*1024);//Größe (in bytes) eines Stücks
//Große Datei als Stream byte für byte auslesen
//https://stackoverflow.com/questions/6914912/streaming-a-large-file-using-php
function downloadStueckweise($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt    = 0;
    $handle = fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, STUECK_GROESSE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($handle);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }

    return $status;
}
if (!empty($_GET['download'])) {
    $pfadUndDatei = strip_tags($_GET['download']);
    if (file_exists($pfadUndDatei)) {
        //Datei vorhanden!
        DownloadGrosseDatei($pfadUndDatei);
    } else {
        //Wenn die Datei nicht vorhanden ist, dann...
        exit('<h1>Sie haben einen Fehler verursacht!</h1>');
    }//ENDE: else ==> if (file_exists())
}//ENDE: if (!empty($_GET['download']))