My download Function corrupting the file

Asked

Viewed 69 times

0

I created a download Function but it’s corrupting the files and I can’t find the reason! Downloads normally, but when I open the file it reports that the file is in an unknown or damaged format.

public function download($token, $renomear) {
    $local_file = 'download/' . $token . '.zip';
    $download_file = $renomear . '.zip';

    // set the download rate limit (=> 20,5 kb/s)
    $download_rate = 20.5;
    if (file_exists($local_file) && is_file($local_file)) {
        header('Cache-control: private');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . filesize($local_file));
        header('Content-Disposition: filename=' . $download_file);
        header('Connection: Close');

        flush();
        $file = fopen($local_file, "r");
        while (!feof($file)) {
            // send the current file part to the browser
            print fread($file, round($download_rate * 1024));
            // flush the content to the browser
            flush();
            // sleep one second
            sleep(1);
        }
        fclose($file);
    } else {
        $pdo = new PDO\Database();
        $insertStatement = $pdo->insert(array(
                    "item_token" => $token,
                    "valor" => "Erro: o arquivo não existe!"
                ))
                ->into("file_log");
        $insertStatement->execute();
        header("Refresh: 0");
        die();
    }
}
  • managed to find the problem?? I tested your code and had an expected behavior.

  • It works with some and with others it even downloads but when I will open appears a corrupt file warning!

1 answer

3


A possibility and use the readfile, and change Content-Type to header('Content-Type: application/zip');

public function download($token, $renomear) {
    $local_file = 'download/' . $token . '.zip';    
    $download_file = $renomear . '.zip';

    $download_rate = 20.5;
    if (file_exists($local_file) && is_file($local_file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');      
        header('Content-Disposition: filename=' . $download_file);
        header('Cache-Control: must-revalidate');
        header('Content-Length: ' . filesize($local_file));
        readfile($local_file);
        exit;

    } else {        
        $pdo = new PDO\Database();
        $insertStatement = $pdo->insert(array(
                    "item_token" => $token,
                    "valor" => "Erro: o arquivo não existe!"
                ))
                ->into("file_log");
        $insertStatement->execute();
        header("Refresh: 0");        
        die();
    }
}

readfile

  • Thanks, apparently everything worked out now!

  • You would know how to add $download_rate to limit download speed?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.