Force download with php makes file come corrupted

0

I use this code to force download:

            function filesizecurl($arquivo)
        {
            if (is_file($arquivo) === false) {
                return false;
            }

            $arquivo = realpath(preg_replace('#^file:#', '', $arquivo));

            $ch = curl_init('file://' . ltrim($arquivo, '/'));

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Faz o retorno ser salvo na variável
            curl_setopt($ch, CURLOPT_HEADER, 1); //Faz retornar os headers
            curl_setopt($ch, CURLOPT_NOBODY, 1); //Evita retornar o corpo

            $headers = curl_exec($ch);
            curl_close($ch);

            $ch = null;

            //Com preg_match extraímos o tamanho retornado de Content-Length
            if (preg_match('#(^c|\sc)ontent\-length:(\s|)(\d+)#i', $headers, $matches) > 0) {
                return $matches[3];
            }

            return false;
        }

        $file_path = DIR_ARQUIVOS.$key.'.zip';
        $file_name = $key.'.zip';
        $new_name = $sql->getKeyName($key);

        $sql->addDownloadQuantityFile($key);

        set_time_limit(0);

        header('Content-Type: "application/zip"');
        header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Pragma: no-cache');
        // Envia o arquivo para o cliente
        readfile($file_name);

And in index.php:

if (preg_match('#pages/download\.php$#', $pag) > 0) 
{
    include $pag;
    exit;
}

and the .zip file is corrupted, how do I resolve this?

    
asked by anonymous 01.04.2017 / 20:32

1 answer

1

It may be that you have some part of the code that is 'messing up' the buffer, and it ends up corrupting the file, try to clear the buffer before giving the readfile

header('Content-Type: "application/zip"');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');

ob_clean();
flush();
// Envia o arquivo para o cliente
readfile($file_name);
exit;
    
02.04.2017 / 08:51