Having the name of the file:
$filename = 'test.zip';
How to make a PHP script send a file to be downloaded?
Two forms are presented: a more direct and simple and another that is responsible for checking errors, mainly with large files that could exceed the memory limit, and offer to restore an interrupted download. In both, it is very important that the script does not write anything, not even a blank line before <?php
, since HTTP headers .
Simple form
It works perfect for the vast majority of files, as long as the size does not exceed the memory limit.
//Sin notificaciones, y que el server no comprima
@ini_set('error_reporting', E_ALL & ~ E_NOTICE);
@ini_set('zlib.output_compression', 'Off');
//Encabezados para archivos .zip
header('Content-Type: application/zip');
header('Content-Transfer-Encoding: Binary');
//El nombre predeterminado que verá el cliente
header('Content-disposition: attachment; filename="' . basename($filename) . '"');
//Que no haya límite en la ejecución del script
@set_time_limit(0);
//Imprime el contenido del archivo
readfile($filename);
Download the file in blocks, allowing summary downloads using http_range *
//esconder notificaciones
@ini_set('error_reporting', E_ALL & ~ E_NOTICE);
//que el server no comprima
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 'Off');
// parsear el nombre del archivo
$path_parts = pathinfo($filename);
$file_name = $path_parts['basename'];
$file_ext = $path_parts['extension'];
$file_path = $file_name; //Si se descarga de otra ubicación, cambiar por: $file_path = './carpeta/descargas/' . $file_name;
$is_attachment = true; //Como adjunto (cambiar a false si es un stream, por ej. audio o video)
// existe el archivo?
if (is_file($file_path))
{
$file_size = filesize($file_path);
$file = @fopen($file_path,"rb");
if ($file)
{
// encabezados, y sin caché
header("Pragma: public");
header("Expires: -1");
header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
if ($is_attachment)
header("Content-Disposition: attachment; filename=\"$file_name\"");
else
header('Content-Disposition: inline;');
// mime type según la extensión (agregar otra si falta)
$ctype_default = "application/octet-stream";
$content_types = array(
"exe" =--> "application/octet-stream",
"zip" => "application/zip",
"mp3" => "audio/mpeg",
"mpg" => "video/mpeg",
"avi" => "video/x-msvideo",
);
$ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default;
header("Content-Type: " . $ctype);
// http_range si hay gestión de descarga
$range = '';
if(isset($_SERVER['HTTP_RANGE']))
{
list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if ($size_unit == 'bytes')
{
list($range, $extra_ranges) = explode(',', $range_orig, 2);
}
else
{
header('HTTP/1.1 416 Requested Range Not Satisfiable');
exit;
}
}
list($seek_start, $seek_end) = explode('-', $range, 2);
$seek_end = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)),($file_size - 1));
$seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);
if ($seek_start > 0 || $seek_end < ($file_size - 1))
{
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$file_size);
header('Content-Length: '.($seek_end - $seek_start + 1));
}
else
header("Content-Length: $file_size");
header('Accept-Ranges: bytes');
set_time_limit(0);
fseek($file, $seek_start);
// imprimir el archivo
while(!feof($file))
{
print(@fread($file, 1024*8)); //leer 8KB
ob_flush();
flush();
if (connection_status()!=0)
{
@fclose($file);
exit; //error
}
}
// terminó OK
@fclose($file);
}
else
{
// no se pudo abrir el archivo
header("HTTP/1.0 500 Internal Server Error");
}
}
else
{
// no existe el archivo
header("HTTP/1.0 404 Not Found");
}
exit;
/**
* Copyright 2012 Armand Niculescu - media-division.com
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
* Modified version of the code of Armand Niculescu