Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created January 28, 2021 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/ee98f2c3de7ef9c0d264eab58053af30 to your computer and use it in GitHub Desktop.
Save parzibyte/ee98f2c3de7ef9c0d264eab58053af30 to your computer and use it in GitHub Desktop.
<?php
static function servirArchivoParaDescargar($idArchivo)
{
$archivo = Gestor::obtenerUnoPorId($idArchivo);
$rutaAbsoluta = Gestor::obtenerRutaAbsoluta($archivo->nombre_real);
$tamanio = filesize($rutaAbsoluta);
$tamanioFragmento = 5 * (1024 * 1024); //5 MB
set_time_limit(300);
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Pragma: no-cache");
header('Content-Length: ' . $tamanio);
header(sprintf('Content-disposition: attachment; filename="%s"', $archivo->nombre_original));
// Servir el archivo en fragmentos, en caso de que el tamaño del mismo sea mayor que el tamaño del fragmento
if ($tamanio > $tamanioFragmento) {
$manejador = fopen($rutaAbsoluta, 'rb');
// Mientras no lleguemos al final del archivo...
while (!feof($manejador)) {
// Imprime lo que regrese fread, y fread leerá N cantidad de bytes en donde N es el tamaño del fragmento
print(@fread($manejador, $tamanioFragmento));
ob_flush();
flush();
}
// Cerrar el archivo
fclose($manejador);
} else {
// Si el tamaño del archivo es menor que el del fragmento, podemos usar readfile sin problema
readfile($rutaAbsoluta);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment