Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created January 26, 2021 22:36
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/bb348fdd3a2e594475d5573187c05643 to your computer and use it in GitHub Desktop.
Save parzibyte/bb348fdd3a2e594475d5573187c05643 to your computer and use it in GitHub Desktop.
<?php
$rutaAbsoluta = "Cuphead.zip"; // La ubicación del archivo. En mi caso está en el mismo directorio que este script
$nombreArchivo = "Cuphead.zip"; // El nombre que se le sugiere al usuario cuando guarda el archivo. Solo el nombre, NO la ruta absoluta
$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"', $nombreArchivo));
// 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