Home > Php > Descarga de archivos con PHP

En esta ocasión les explico como realizar a la fuerza la descarga de un archivo, ya que en algunas ocasiones deseamos descargar determinado archivo y este se visualiza directamente en el navegador.

La manera mas fácil seria esta:

$file = $_GET['file'];
header("Content-disposition: attachment; filename=$file");
header("Content-type: application/octet-stream");
readfile($file);

Pero este método no es muy seguro, porque podrian descargar nuestros archivos del servidor como el index.php, ademas tendremos que verificar si el archivo existe o no,  el modo seguro seria el siguiente:

if (!isset($_GET['file']) || empty($_GET['file'])) {
 exit();
}
$root = "images/";
$file = basename($_GET['file']);
$path = $root.$file;
$type = '';

if (is_file($path)) {
 $size = filesize($path);
 if (function_exists('mime_content_type')) {
 $type = mime_content_type($path);
 } else if (function_exists('finfo_file')) {
 $info = finfo_open(FILEINFO_MIME);
 $type = finfo_file($info, $path);
 finfo_close($info);
 }
 if ($type == '') {
 $type = "application/force-download";
 }
 // Definir headers
 header("Content-Type: $type");
 header("Content-Disposition: attachment; filename=$file");
 header("Content-Transfer-Encoding: binary");
 header("Content-Length: " . $size);
 // Descargar archivo
 readfile($path);
} else {
 die("El archivo no existe.");
}

Ahora solo colocamos nuestro enlace de descarga.

<a href=”download.php?file=imagen.jpg”>Descargar</a>

y eso es todo , espero que le sirva.